
/*!
 * X weibo JavaScript Library v1.1
 * http://x.weibo.com/
 * 
 * Copyright 2010 SINA Inc.
 * Date: 2010/10/28 21:22:06
 */

// 当ready.js一些功能复用的比较多时可经重构后放到本JS文件来，再在ready.js里引用。

(function(X, $){

var 
	undefined,
	ui = X.ui, 
    Util = X.util, 
    doc = document, 
    Base = ui.Base, 
    base = Base.prototype,
    NULL = null,
    TRUE = true,
    FALSE = false,
    T = X.ax.Tpl, 
    Req = X.request,
	hideCls = 'hidden',
    exceedCS = 'out140',
    MB = X.use('msgbox'),
	getCfg = X.getCfg,
	getUid = X.getUid,
	getWb = X.getWb,
	setWb = X.setWb,
    getText = X.lang.getText,
    win = this;
    

if(!X.mod)
    X.mod = {};
    
//刷新页面
function Refresh() {
    win.location.reload();
}

var mod = X.mod;
/*
$(function(){
    $('.dest-nav').click(function(){
        X.use('emotion').setSelectionHolder( X.use('SelectionHolder', {elem:$('.search-input')[0]}))
        .showAt('.search-input');
    })
})
*/

/**
 * @class Xwb.mod.emotion
 * 表情弹窗
 * @extends Xwb.ui.Box
 * @singleton
 */
X.reg('emotion', function(p){

var inst = X.use('Box', {
    
	contentHtml: 'Loading',
    
    boxOutterHtml : 'ArrowBoxBottom',
    
    cs : 'win-emotion',
    
    appendTo : doc.body,
    
    closeable : true,
        
    actName : 'em',
    
    contextable : true,
    
    actionMgr : true,

	emotions: null,

	//当前选中的分类
	$categorySelected: null,

	//当前显示的表情列表
	$categoryShowed: null,

	//分类索引->数据映射
	cateMaps: {},
    
    onactiontrig : function(e){
        switch(e.data.e){
            case 'em':
                if( this.onselect ){
                    if( this.onselect(this.findEmotionText(e), e) === false)
                        return;
                }
                this.display(false);
            break;

			case 'sc': //选择分类
				//console.debug(e);
				this.emSwitch(e.data.idx, e.src);
			break;
        }
    },
    
    setHandler : function(hd){
        this.onselect = hd;
        return this;
    },
    
    setSelectionHolder : function(selHolder, oninsert, scope){
        this.setHandler(function( selected ){
            selHolder.insertText(selected);
            oninsert && oninsert.call(scope||this, selHolder, selected);
        });
        return this;
    },
    
    //osTop : offsetTop
    showAt : function(anchor){
        var off = $(anchor).offset();
        off.left -= 24;
        off.top += 20;
        this.offset(off)
            .display(true)
            .trackZIndex(10011);
			
		var $win = $(win), h = 270,
        win_h = parseFloat($win.height())
		,wh = $(document).scrollTop();
		var last = off.top + h - (wh + win_h);
		if(last){
			if(Util.ie6)
				$('html,body').scrollTop(wh + last);
			else
				$('html,body').animate( { 'scrollTop': wh + last } , 400 );
		}
		if(p && p.emoIndex) this.jq().css('z-index', p.emoIndex);
    },

	initEmotion: function(resp) {
		if (resp.isOk())
		{
			var data = resp.getData();
			
			var 

				emotions = {},
				hots = [],

				//模板值
				category = [],
				hotFaces = [],

				//分类索引ID
				cateIdx = 0,
				cateMaps = {};;


			$.each(data, function(i, e) {
				if (e.type != 'face')
				{
					return;
				}

				var cateName = e.category ? e.category: '默认';
				if (!emotions[cateName])
				{

					emotions[cateName] = [e];
					
					cateMaps[cateIdx] = emotions[cateName];

					category.push(['<a href="#" rel="e:sc,idx:',cateIdx,'">',cateName,'</a>'].join(''));

					cateIdx++;
					
				} else {
					emotions[cateName].push(e);
				}
				
				if (e.is_hot)
				{
					hots.push(['<a href="#" rel="e:em" title="' ,e['phrase'] ,'"><img width="22px" height="22px" src="', e['url'] ,'" /></a>'].join(''))
				}
			});

			var faceHtml = [];

		    // 过滤重复表情
		    var hot = 0;
    		$.each(emotions['默认'], function(i, fc) {
    			if(fc['is_hot']) hot++;
    			if(!fc['is_hot'] || hot>15)
    			    faceHtml.push(['<a href="#" rel="e:em" title="' ,fc['phrase'] ,'"><img width="22px" height="22px" src="', fc['url'] ,'" /></a>'].join(''));
    		});

			if (hots.length > 15)
			{ //热门的只显示１５个
				hots = hots.slice(0, 15);
			}

			var assigns = {
				category: category.join(''),
				faces: faceHtml.join(''),
				hotList: hots.join('')
			};
			
			var $show = $(T.parse('EmotionBoxContent', assigns));

			this.jq('#xweibo_loading').hide();
			this.jq('#xwb_dlg_ct').append($show);

			this.$categorySelected = this.jq('#cate>a:first').addClass('current');
			this.$categoryShowed = this.jq('#flist0');

			this.emotions = emotions;
			this.cateMaps = cateMaps;
		}
	},

	// 创建表情显示区
	createEmArea: function(i) {

		var faces = this.cateMaps[i];
		var html = ['<div class="e-list" id="flist' + i + '">'];

		$.each(faces, function(i, fc){
			html.push(['<a href="#" rel="e:em" title="' ,fc['phrase'] ,'"><img width="22px" height="22px" src="', fc['url'] ,'" /></a>'].join(''));
		});

		html.push('</div>');

		return $(html.join(''));
	},
	
	//切换分类
	emSwitch: function(i, src) {
		var $src = $(src);
		var current = 'current';

		if ($src.hasClass(current))
		{
			return;
		}
		this.$categorySelected.removeClass(current);
		this.$categorySelected = $src.addClass(current);

		this.$categoryShowed.addClass(hideCls);

		if (i > 0)
		{
			this.jq('#hotEm').addClass(hideCls);
		} else {
			this.jq('#hotEm').removeClass(hideCls);
		}
			

		var $show = this.jq('#flist'+i);

		if (!$show.length)
		{
			$show = this.createEmArea(i).appendTo(this.jq('#box'));
		}

		this.$categoryShowed = $show.removeClass(hideCls);
	},

	// 加载表情数据
	loadEmotion: function() {
		var self = this;
		Req.getEmotions(function(r) {
			self.initEmotion(r);
		});
	},

	onViewReady: function() {
		this.loadEmotion();
	},
	
    // 定义如何获得表情文本
    findEmotionText : function(e){
        return e.src.title;
    }
});

// override function -> object
X.reg('emotion', inst, true);

return inst;
});

/**
 * @class Xwb.mod.forwardBox
 * 转发对话框
 * @extends Xwb.ui.Dialog
 * @singleton
 */
X.reg('forwardBox', function(){

var inst = X.use('Dlg', {
    cs : 'win-forward',
    appendTo : doc.body,
    autoCenter : true,
    dlgContentHtml : 'ForwardDlgContentHtml',
    title: getText('转发到我的微博'),
    defBtn : 'forward',
    buttons : [
        {title: getText('转 发'), id:'forward', cs:'btn-s1'},
        {title: getText('取 消'), id:'cancel', cs:'btn-s1 btn-s1-gray'}
    ],

    checkText : function(){
        var v = $.trim( this.jqInputor.val() );
        var left = Util.calWbText(v);
        if (left >= 0)
            this.jqWarn.html(getText('您还可以输入{0}字', left));
        else
            this.jqWarn.html( getText( '已超出{0}字', Math.abs(left) ) );
        this.jqWarn.checkClass(exceedCS,left<0);
        return left>=0 && v;
    },
    
    
    onViewReady : function(){
        this.jq('#xwb_face_trig')
            .click(Util.bind( this.onFaceTrig, this ));
            
        this.jqInputor = this.jq('#xwb_fw_input');
        this.jqWarn    = this.jq('#xwb_warn_tip');
        this.jqContent = this.jq('#xwb_forward_text');
        this.jqLabelCt = this.jq('#xwb_fw_lbl');
        
        this.jqInputor.bind('keyup', Util.bind( this.onInputorKeyup, this ));
        this.selectionHolder = X.use('SelectionHolder', {elem:this.jqInputor[0]});
        this.atWho = X.use('atWho',{
            appendTo : doc.body,
            Inputor : this.jqInputor,
            autoRender : true
        });
    },
    
    onInputorKeyup : function(e){
        if(this.checkText()){
            // ctrl + enter post
            if(e.ctrlKey && ( e.which == 13||e.which == 10 ))
                this.submit();
        }
    },
    
    onFaceTrig : function(e){
        X.use('emotion')
         .setSelectionHolder( this.selectionHolder , this.checkText, this)
         .showAt(e.target);
        return false;
    },
    
    setContent : function(wbId, wbData, uid){
        
        this._predCfg = { id : wbId, data : wbData, uid : uid };
        
        // Make sure view node is created
        this.jq();
        
        var otherCmts = [], text, inputText;
        if( uid !== wbData.u.id )
            otherCmts.push( T.parse( 'ForwardDlgLabel', {uid:wbId, nick:wbData.u.sn}) );
        
        var rt = wbData.rt;
        if (rt) {
            text = rt.tx;
            inputText = '//@' + wbData.u.sn + ':' + wbData.tx;
            
            //if (rt.u.id != uid) 
                otherCmts.push( T.parse('ForwardDlgLabel', { uid: rt.id, nick: rt.u.sn }) );
        }
        else {
            text = wbData.tx;
            inputText = '';
        }
        
        this.jqContent.text( Util.escapeHtml( text ) );
        this.selectionHolder.setText( inputText );
        this.checkText();
        this.jqLabelCt.html( otherCmts.join('') );
        
        return this;
    },
    
    submit : function(){
        
        if( this.isLoading )
            return false;

        this.isLoading = true;
        
        var v = this.checkText();
        if( v  === '' ){
            v = getText( '转发微博' );
        }else if( !v ){
            this.jqInputor.focus();
            this.isLoading = false;
            return false;
        }
        
        var uids = [];
        this.jq('input[type="checkbox"]:checked').each(function(){
            uids[uids.length] = $(this).val();
        });
        
        var d = this._predCfg;
		var param = $.extend( {_route:X.getModule() },this.getParam());
        Util.disable( this.getButton('forward') , true);
        Req.repost(d.id, v, uids.join(','), Util.getBind(this, 'onSubmitLoad'), { data : param });
    },
	
    getParam : function(){
		return {};
	},
	
    onSubmitLoad : function( e ){
        
        Util.disable( this.getButton('forward') , false);
        this.close();
        // todo : 关闭在tip隐藏后
        if(e.isOk()){
            MB.tipOk('转发成功');
        }
        else MB.tipWarn( e.getMsg( null, getText('微博转发') ));
        this.isLoading = false;
    },
    
    onbuttonclick : function(bid){
        if( bid === 'forward' ){
            this.submit();
            return false;
        }
    }
});

X.reg('forwardBox', inst, true);

return inst;

});

/*!
 * 
 * http://flowplayer.org/tools/toolbox/flashembed.html
 *
 * Since : March 2008
 * Date  :    Wed May 19 06:53:17 2010 +0000 
 * modify by : guolianghu
 * opts.height 高 （必须）
 * opts.width 宽 (必须）
 * opts.id dom-id
 * opts.name dom-name
 * opts.src flash地址 （必须）
 * opts.nocache 禁用cache （可选）
 * opts.w3c 
 * 
 * conf: 配置  （可选）
 */ 
ui.getFlash = function(opts, conf) {
    opts = opts || {};
    
    var width = opts.width,
        height = opts.height,
        src = opts.src,
        nocache = opts.nocache,
        dom_id = opts.id,
        dom_name = opts.name,
	    embed_htmls = ["<embed"],
	    html = [
            '<object',
            'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
        ],
        param = [
            "<param name='allowfullscreen' value='true'>"
//            "<param name='allowscriptaccess' value='always'>"
        ];
	
    var attrs = ['width', 'height', 'name', 'id'], tmpstr;
    
    $.each(attrs, function(i, n){
        var tmpvar = opts[n];
        if (tmpvar) {
            tmpstr = n + '="' + tmpvar + '"';
            embed_htmls.push(tmpstr);
            html.push(tmpstr)
        }
    });
    
    html.push('>');
    
	if (nocache) {
		src += ((src.indexOf("?") != -1 ? "&" : "?") + Math.random());		
	}
    
    //src
    embed_htmls.push('src="' + src + '"');
    param.push('<param name="movie" value="' + src + '">');
    
	// not allowed params
	opts.width = opts.height = opts.id = opts.w3c = opts.src = null;
	opts.onFail = opts.version = opts.expressInstall = null;
	
	for (var key in opts) {
		if (opts[key]) {
			param.push('<param name="'+ key +'" value="'+ opts[key] +'">');
			embed_htmls.push( key + '="' + opts[key] + '"');
		}
	}	

	// FLASHVARS 
	var vars = "";
	
	if (conf) {
		for (var k in conf) { 
			if (conf[k]) {
				var val = conf[k]; 
				vars += k +'='+ (/function|object/.test(typeof val) ? f.asString(val) : val) + '&';
			}
		}
		vars = vars.slice(0, -1);
		param.push( '<param name="flashvars" value="' + vars + '">');
		embed_htmls.push( 'flashvars="' + vars + '"' );
	}

	embed_htmls.push('/>');
	
    html = html.concat(param)
    
    var htmlstr = $.browser.msie ? html.concat(param, '</object>').join(' ') : embed_htmls.join( ' ' );
    //var htmlstr = html.concat(param, embed_htmls, '</object>').join(' ');
    return htmlstr;
}


/**
 * @class Xwb.mod.CmtBox
 * 页面内的评论框
 * @extends Xwb.ui.Base
 */
// pCt 接口方法：afterSend, postWeibo
mod.CmtBox = X.reg('CmtBox', Util.create(Base, {
    actionMgr : true,
    view : 'CmtBox',
    exceedCS : 'over-limit',
    autoH : true,
    wbUid : null,
	commentUrl : Req.youjiComment,
	share : '分享给到微博',
    headPicType:1,
    innerViewReady : function( v ){
		this.wbUid = X.getUid();
        base.innerViewReady.call(this, v);
        this.jqExtra('inputor', 'warn', 'sync');
        this.selectionHolder = X.use('SelectionHolder', {elem:this.jqInputor[0]});
        var self = this;
        this.jqInputor
        .bind('keyup', function(e){
             self.onInputorKeyup(e);
        });
        
        
        this.atWho = X.use('atWho',{
        	appendTo:doc.body,
        	Inputor : this.jqInputor,
        	autoRender : true
        });
		if(this.localComments){
			this.jq('.icon-face-choose').cssDisplay(0);
		}
    },
    
    //表情浮层相对位移
    faceOsTop : 20,
    
    reset : function(){
        this.getView();
        this.selectionHolder.setText('');
        //this.jqSync.attr('checked', false);
        this.checkText();
		
		if(this._param && this._param.data){
			for(var key in this._param.data){
				if(key != '_route' && key !='wid'){
					delete this._param.data[key];
				}
			}
		}
    },
    maxLen : 140*2,
    checkText : function(){
        var ipt = this.jqInputor, v = ipt.val();
        //输入为空
        if (!v || !$.trim(v)) {
            ipt.focus();
            return FALSE;
        }
		//var maxLen = 200*2;this.isReply(ipt.val()) ? 70*2 : 140*2;
		
        var left = Util.calWbText(v, this.maxLen/2);
        if (left < 0) {
            ipt.val(Util.byteCut(v, this.maxLen));
			Util.focusEnd(ipt[0]);
        }
        
        return ipt.val();
    },
    reqReply:function(){
		this.replyUrl.apply(Req,arguments);
	},
	comment:function(){
		this.commentUrl.apply(Req,arguments);
	},
	getParam:function(){
		if(!this._param)
			this._param = {};
			
		if(this._param.data){
			this._param.data._route = X.getModule();
		} else {
			this._param.data = {_route:X.getModule()};
		}
		return { data : $.extend({},this._param.data) };
	},
    
    send : function(){
        if(!this.sending){
            var v = this.checkText();
            if( !v )
                setTimeout( Util.bind(function() { this.jqInputor.focus();}, this), 0 );
            else {
                if(this.sndBtn) 
                    Util.disable( this.sndBtn , true , 'btn-s4-disabled');
                this.sending   = true;
				var replyCmtId = this.jqInputor.data('xwb_reply_cid'),
					regx = new RegExp('^' + getText('回复') + '@.*?: ');
                if( replyCmtId && regx.test(v) )
                    this.reqReply(
                      this.wbId, 
                      replyCmtId, 
                      v, 
                      this.jqSync.attr('checked')?1:0, 
                      this.headPicType, 
                      Util.getBind(this, 'onSendLoad'),
                      this.getParam()
                    );
                else this.comment( 
                      this.wbId, 
                      v, 
                      this.jqSync.attr('checked')?1:0, 
                      this.headPicType, 
                      Util.getBind(this, 'onSendLoad'),
                      this.getParam()
                     );
            }
        }
    },
    
    onSendLoad : function( e ){
        if( e.isOk() ){
           // this.pCt.afterSend(e);
            
			X.fire('Cmt.afterSend',e);
			//更新缓存数据
			var wbList = getCfg('wbList');
			wbList && wbList[this.wbId] && (wbList[this.wbId].comments_count = + wbList[this.wbId].comments_count  + 1);
			
            // 同时发一条微博
            var data = e.getData();
/*             if( false && data.html ){
                this.pCt.postWeibo(data.wb, data.html);
            } */
			if(data.notice){
				X.use('CoinExperience',{notice :data.notice});
				var $ct = $("#commenTotal");
				$ct.length && $ct.html( $ct.html().replace(/(\d+)/,function(c){ return +c+1; }));
			}
			this.reset();
			
        }else {
			this.cmtError(e);
        }
        if(!this.pCt.afterNofocus)
        	this.jqInputor.focus();
        if(this.sndBtn) 
            Util.disable( this.sndBtn , false , 'btn-s4-disabled');
        this.sending = false;
    },
	
	cmtError : function(e){
		MB.tipWarn( e.getMsg() );
		if( e.getCode() == '30000' ) this.reset();
	},
    
    reply : function(cmtId, nick){
        var holder = this.selectionHolder, 
            jq     = this.jqInputor,
            rex    = new RegExp('^' + getText('回复') + '@.*?:');
        this.reset();
        holder.setText( getText('回复') + '@' + nick + ': ' + jq.val().replace(rex, ''));
        jq.data('xwb_reply_cid', cmtId);
        this.checkText();
        setTimeout(function(){ holder.focusEnd(); }, 0);
    },
    
    onFaceTrig : function(e){
        X.use('emotion')
         .setSelectionHolder( this.selectionHolder , this.checkText, this)
         .showAt(e.src, this.faceOsTop);
        return false;
    },
        
    onInputorKeyup : function(e){
        if(this.checkText()){
            // ctrl + enter post
            if(e.ctrlKey && ( e.which == 13||e.which == 10 ))
                this.send();
        }
    },
    
    onactiontrig : function(e){
        switch ( e.data.e ){
            // 点击图标
            case 'ic' :
                this.onFaceTrig(e);
                break;
                
            // 点击评论按钮
            case 'sd' :
                if(!this.sndBtn)
                    this.sndBtn = e.src;
                this.send();
                break;
			case 'cw' : //分享到weibo				
				this.shareWeibo(e);
			break;
            
            //表情
            case 'face':
                //console.log(e);
                X.use('emotion', {emoIndex:this.emoIndex})
                .setSelectionHolder(
                    X.use('SelectionHolder', {
                            elem : this.jqInputor[0]
                        }
                    )
                )
                .showAt(e.src, this.faceOsTop);
            break;
        }
    }
}));

/**
 * @class Xwb.mod.CommentArea
 * 页面内的单条微博的评论区域
 * @extends Xwb.ui.Base
 */
// parent container interface :
// function:afterSend
// postWeibo

var CommentArea = mod.CommentArea = X.reg('CmtArea', Util.create(Base, {
    
    view : 'CommentArea',
    
    readSize : 10,
    
    cmtType : 1,
    
    hdPicSz : 30,
    
    cmtCount : 0,
    
    page : 1,
	
	startPage : 1,
	
	startCursor : '', //兼容用corsor取数据的分页
    
    cmtPageSz : 20,
	
	first : true,
    
    //回复自己的开关
    canReply : true,
    
    //是否显示回复的总开关
    showReply : true,
	
	showEmotion : true,
	
    // html
    cmtBoxHtml:'CmtBox',
    commentHtml : 'Comment',
    // 开启action点击监听
    actionMgr : true,
    cmtBox : 'CmtBox',
    
    initUI : function(){
        // prepare for templting
				
        this.cmtUrl = Req.mkUrl('show', '', 'id='+this.wbId);
        this.jqExtra('pre','first','next');

        base.initUI.call(this);
    },
    
    getFromUser : function(){
        if(!this.wbUid) {
		  var youji = getCfg('youji');
		  if(youji){
			this.wbUid = youji.sina_uid;
		  } else {
			var wb = getWb(this.wbId);
			this.wbUid = wb && wb.u.id;
		  }
		}
        return this.wbUid;
    },
    
    innerViewReady : function( v ){
        base.innerViewReady.call(this, v);
        this.jqExtra('cmtCt', 'more', 'lefCnt');
        this.initCmtBox();
	    X.on('Cmt.afterSend',Util.getBind(this,'afterSend') );
	    this.jq('#inputor').focus(function(){
			$(this).addClass('style-focus');
		}).blur(function(){
			$(this).removeClass('style-focus');
		});
	   
    },

    decorateLoading : function(){
        if( this.isLoading ){
            $(T.get('Loading')).appendTo(this.getView().parentNode);
        }else $(this.getView().parentNode).find('#xweibo_loading').remove();
        this.display(!this.isLoading);
    },
    
    initCmtBox : function(){
       this.cmtBox  = X.use('CmtBox', {
            view : this.jq('#cmtBox')[0],
            wbId : this.wbId,
			localComments : this.localComments,
            pCt  : this,
			commentUrl : this.commentUrl,
			replyUrl : this.replyUrl,
            headPicType : this.hdPicSz==30?1:2,
			maxLen : this.maxLen || 140*2
       });
	   this.cmtBox.getView();
	   
	   //本地评论没有发布微博隐藏 分享给到微博
	   if(this.localComments ){
			if(getCfg('wbList')){
				var wbList = getCfg('wbList');
				for(var wbid in wbList)
					this.cmtBox._param = {data:{wid:wbid}};
			} else {
				this.cmtBox.jqSync.closest('div').cssDisplay(0);
				this.cmtBox._param = {data:{}};
			}
	   }
	   
	   if(this.trigEl){
			var self = this;
			$(this.trigEl).click(function(){
				self.cmtBox.jqInputor.focus();
			});
	   }
    },
    
    load : function(callback){
        // 确保view已创建
        this.getView();
        if( !this.isLoading ){
            this.isLoading = true;
            this.decorateLoading();
            callback && ( this.onload = callback );
            this.getComments(this.wbId, this.page, this.cmtType,  Util.getBind(this, 'onCmtsLoad'));
        }
		
    },
	getComments:function(){
		this.getCommentUrl.apply(Req,arguments);

/* 		if(this.localComments){
			Req.getYoujiComments.apply(Req,arguments);
		} else {
			Req.getComments.apply(Req,arguments);
		} */
	},
        
    // callback by cmtBox
    postWeibo : function(wbData, htmls){
       // X.fire('wb.create', {data:wbData, html:htmls});
    },
    
    // callback by cmtBox
    afterSend : function(e){
        var jq = $(this.createCmtUI(e.getData().comment || e.getData().data || e.getData()));
        this.jqCmtCt.prepend( jq );
        this.jqCmtCt.cssDisplay(true);
        this.updateCmtCountUI(1, true);
		this.itemHover(jq);
        // 解析评论里的短链接
        /*
        X.mod.shortlink.render(jq, function(urlInfo, aHref){
            aHref.title = urlInfo && urlInfo.url || getText('无效链接');
        });
        */
		var img = jq.find('.replyImg')
		if(img.length){
			var $t = img, src = $t.attr('_src');			
			Util.drawImage(src, 150, 200,function(obj){
				$t.attr('src',src).css({width:obj.width, height:obj.height})
			});
		};
		if(getCfg('uid'))
			X.use('usersCard',{items:jq.find('.user_card')});
    },
    
	itemHover:function(itemJq){
		itemJq.hover(function(){
			$(this).find('.ico-report , .ico-del-s1, .actions').cssDisplay(1);
		},function(){
			$(this).find('.ico-report , .ico-del-s1, .actions').cssDisplay(0);
		});
	},
    // 评论返回后
    onCmtsLoad : function( e ){
        if( e.isOk() ){
            var data = e.getData();
            var num = this.createListUI( e );
			var total = data.total;
            total && this.updateCmtCountUI( total );
            data.num = num;
            this.updateCmtPageUI(data);
        }
        
        this.isLoading = false;
        this.decorateLoading();
        if( this.onload )
            this.onload( e );
        /*
        console.log('CommentArea init')    ;
        
        this.atWho = X.use('atWho',{
        	appendTo:doc.body,
        	Inputor : this.cmtBox.jqInputor,
        	autoRender : true
        });
        */
		if(this.first){
			this.first = false;
		}else{
			$(document).scrollTop(this.jq().offset().top);
		}
    },
    
    //从getcomments接口解析出评论数据
    getRespListData  : function( data ){
        return data.tips || data.list || data;
    },
    
    //解释结果里的总数
    getRespTotal : function(data) {
        return data.total || data.total_number;
    },
    
    // 创建评论列表
    createListUI : function( e ){
		var isPoint = this.type == 'pointComment'? true : false; //点评(true)
		
        this.jqCmtCt.empty();
        var listData = e.getData(),
            commentsList = this.getRespListData(listData),
            total = this.getRespTotal(listData);
        var lef = total - Math.min( listData.limit, total );
        var htmls = [], self = this;
        $.each(commentsList, function(cmt, d){
			if(typeof d == 'object')
				htmls[htmls.length] = self.createCmtUI.call(self, d, cmt);
        });
        if(htmls.length){
            this.jqCmtCt.html( htmls.join('') );
			if(this.type == 'youji' && total>=200) total = 200+"+";
			this.jq("#commenTotal").html( "共"+total+"条评论:");
           if( lef ){
                this.jqMore.cssDisplay(true);
                this.jqLefCnt.text(lef);
            }else this.jqMore.cssDisplay(false);
            this.jqCmtCt.cssDisplay(true);
        }else {
            this.jqCmtCt.cssDisplay(false);
            this.jqMore.cssDisplay(false);
			if(isPoint){
				this.jqCmtCt.parent().append(T.tpls.onPointComment);
			}				
        }
		
		this.jq('ul img.replyImg').each(function(){
			var $t = $(this), src = $t.attr('_src');			
			Util.drawImage(src, 150, 200,function(obj){
				$t.attr('src',src).css({width:obj.width, height:obj.height})
			});
			
		});
		if(getCfg('uid'))
			X.use('usersCard',{items:this.jqCmtCt.find('.user_card')});
		
		this.itemHover(this.jqCmtCt.find('li'));
        return htmls.length;
        
        // 解析评论里的短链接
        /*
        X.mod.shortlink.render(this.jqCmtCt, function(urlInfo, aHref){
            aHref.title = urlInfo && urlInfo.url || getText('无效链接');
        });
        */
    },
    
    createCmtUI : function(cmt, id){
        var wbUid = this.getFromUser(),
			UID = getUid(),
            user = cmt.user,
            uid = cmt.uid || user.uid;
        if (id) cmt.sid = id;
        cmt.verifiedHtml = user.verified_html;
        cmt.usrUrl= user.profileUrl;
        cmt.picSz = this.hdPicSz;
        cmt.time  = cmt.create_at;
		cmt.level = 'LV.'+ (cmt.level || user.level);
		cmt.canReply = true;  //小组、印象的评论，是否可以回复自己
        if (wbUid == UID || uid == UID ){
            if(uid == UID)
				cmt.canDel = true;
			cmt.canReply = false; //小组、印象的评论，是否可以回复自己
		}
		//小组评论同样使用该微博控件,但没有覆盖createCmtUI该方法,因此插这段代码进来
		else if('group.topic' === getCfg('page') &&  cmt.isGroupAdmin ){
			cmt.canDel = true;
		}
		else
			cmt.hasrep = true; //自己不能出现举报

		if(cmt.ext && cmt.ext.imgUrl){
			cmt.ext._imgUrl = cmt.ext.imgUrl.replace(":","\\:");
		}

		var Regx = getCfg('routeMode') == 3 ? /^(回复<a href=\"\/space\.ta\/id-.+\">.+<\/a>):(.+)/ : /^(回复<a href="\/space\.ta&id=.+\">.+<\/a>:)(.+)/;
		
		if(this.localComments && cmt.ext && cmt.ext.imgUrl){
			cmt.hasimg = cmt.ext.imgUrl;
			if(Regx.exec(cmt.text)){
				var arr = Regx.exec(cmt.text);
				cmt.text1 = arr[1]  + ' 的图片:';
				cmt.text2 = arr[2];
			}else{
				cmt.text3 = cmt.text;
			}
		}else{
			cmt.text3 = cmt.text;
		}
		cmt.user_card = 'user_card';
		//处理马甲帐号
		if(cmt.uid == '100' && cmt.ext){
			var ext = cmt.ext;
			ext.screen_name && (cmt.nick = ext.screen_name);
			if(ext.profile_image_url){
				cmt.profileImg = ext.profile_image_url;
				cmt.img = encodeURIComponent(ext.profile_image_url);
			}
			cmt.sid = ext.uid;
			delete cmt.level;
			//cmt.user_card = '';
			cmt.usrUrl = 'http://weibo.com/u/'+ext.uid;
			cmt.sina = '新浪微博';
			cmt.open = 'target=_blank';
		}
        if (user.profileImg) {
            cmt.profileImg = user.profileImg;
        }
        $.each({uid: 'uid', 'nick' : 'nickname'}, function(k, tk){
            var v = user[tk];
            if (v) {
                cmt[k] = v;
            }
        })
		
		if(this.type == 'pointComment'){
			cmt.agree = false;
			cmt.oppose = false;
			if(cmt.st == 1 || cmt.st == 3){
				cmt.agree = true;
			}
			if(cmt.st == 2 || cmt.st == 3){
				cmt.oppose = true;
			}
		}
		cmt.showReply = this.showReply;
        return T.parse( this.commentHtml, cmt );
    },
    
    updateCmtPageUI : function(pageInfo){
        var total = this.getRespTotal(pageInfo),
            count = this.pagecount || Number(pageInfo.limit);
		if(this.newSystem){
			var curPage = this.startPage;
			
			if( X.getCfg('page') === 'group.topic' ){  // 小组页评论的当前页,以返回的信息 pageInfo.page 为准
				curPage = pageInfo.page;
			}
			//if(this.type == '' && pageInfo.next_cursor != -1){
			else if(pageInfo.next_cursor && pageInfo.next_cursor != -1){
				curPage = Math.ceil(pageInfo.next_cursor/pageInfo.count) || curPage;
			}
			//var count = pageInfo.limit? Number(pageInfo.limit) : pageInfo.count;
			if(total !=0 && (total / count >1)&& !this.pages ){
				var self = this;
				this.pages = X.use('Page',{
							total : total,
							pageSize : count,
							curPage : curPage,
							id : 'page_1',
							appendTo : this.jq('#pageArea'),				
							loadData : function( page, fn){
								self.goPage(page);
								//self.load();
								fn && fn();
								
							}	
						});
			}
		}else{	
			// 如果存在分页按钮
			if(this.jqPre.length){
				this.jqPre.cssDisplay(this.page !== 1);
				// 第三页后显示首页按钮
				this.jqFirst.cssDisplay(this.page >= 3);
				this.jqNext.cssDisplay(pageInfo.total > pageInfo.limit*this.page);
			}
		}
    },
    
    updateCmtCountUI : function(count, cal){
        if( this.trigEl ){
            var txt = getText('评论');
            
            if(cal===undefined){
                $ (this.trigEl).text( txt + '('+count+')');
                this.cmtCount = count;
            }else { 
                this.cmtCount += count;
                $ (this.trigEl).text( txt + '('+this.cmtCount+')');
            }
        }
    },
    
    onactiontrig : function(e){
        switch ( e.data.e ){
            // 点击回复
            case 'rp' :
                this.onReplyTrig(e);
                break;
            case 'dl':
                this.onDelTrig(e);
                break;
            case 'nx' :
                this.goPage(this.page+1);
                break;
            case 'pr' :
                this.goPage(this.page-1);
            break;
            case 'fi':
                this.goPage(1);
            break;
			case 'xrep':
				e.stopPropagation(false);
			break;
			//点评列表
			case 'uforns' :
				e.stopPropagation(false);				
			break;
			case 'rpi':
				this.replyPage(e);
			break;
			case 'sdr' :
			    this.pointReply(e);
			break;
			case 'rpl' :
				this.pointListReply(e)
			break;	
			case 'toC':
				this.toPonitCmt();
			break;
        }
    },
    delComment:function(){
		if(this.localComments){
			Req.youjiDelComment.apply(Req,arguments);
		} else {
			Req.delComment.apply(Req,arguments);
		}
	},
    onDelTrig : function(e){
        var self = this;
		if(!self.deletingCmt){
			MB.anchorConfirm(e.src, getText('确定要删除该评论吗？'), function(bid){
				if(bid === 'ok' && !self.deletingCmt){
					self.deletingCmt = true;
					self.delComment(e.get('c'),e.get('rid'),function(re){
						var cmtEl = e.getEl('c');
						if(re.isOk()){
							$(cmtEl).remove();
							self.updateCmtCountUI(-1, true);
							if(self.cmtCount == 0)
								self.cmtBox.jqInputor.focus();
						}else MB.tipError(re.getMsg());
						self.deletingCmt = false;
					});
				}
			});
		}
    },
    
    onReplyTrig : function( e ){
        var jq = this.jq();
        var off = this.offsetsTo(win);
        if(off[1] < 0){
            //跳到可视范围
            //增强体验
            //if(jq[0].scrollIntoView)
            //    jq[0].scrollIntoView();
			$(document).scrollTop(jq.offset().top - 45);
        }
        var cmtId = e.get('c'),
            nick  = e.get('n');
			
		this.cmtBox.reply(cmtId, nick);
		if(this.localComments){
			$.extend(this.cmtBox._param.data,{ imgUrl : e.get('imgUrl'), wcid : e.get('rid') });
		}
    },
    
    goPage : function(page){
        if(this.topCmtBox && this.topCmtBox.getView().scrollIntoView)
            this.topCmtBox.getView().scrollIntoView();
        this.page = page;
        this.load();
    }
}));


/**
 * @class Xwb.mod.MBlogCmtArea
 * 具体微博的评论区域
 * @extends Xwb.mod.CommentArea
 */


//自动完成类
mod.AutoComplete = X.reg('AutoComplete', Util.create(ui.Layer, function(proto){
    
    return {        
        focused: FALSE,
        
        //输入框
        inputor : null,
        
        showed : FALSE,
        
        enabled : TRUE,
        
        checkChange : FALSE,
        
        //延时检查值的变化
        checkDelay : 0,
        checkTimer : null,
        
        contextable : TRUE,
        
        hidden : TRUE,
        
        val : NULL,
        
        
        //默认文字
        defaultText : '',
        
        selectCls : 'selected',
        selectNext: $.noop,
        selectPrev : $.noop,
        
        onkeyup : function(e){
            //检查
			var code = e.keyCode;
			
            if (this.checkChange) {
				if((code == 38 || code == 40)) return;
                this.checkVal();
            }
        },
        
        onkeydown : function(e) {
            switch (e.keyCode) {
                case 38:
                    this.getData() && this.selectPrev();
                    return false;
                break;
                
                case 40:
                    this.getData() && this.selectNext();
                    return false;
                break;
                
                case 13:
					return this.onEnter(e);
                break;
            }
        },
        
        //回车
        onEnter : $.noop,
        
        getData : $.noop,
        
        onfocus : function(){
            this.checkDefault(TRUE);
            this.focused = TRUE;
			this.checkVal();
        },
        
        onclick : function(e){
            return false;
        },
        
        checkDefault : function(isfocus) {
            //显示默认文字
            var val = this.inputor.val(),
                defaultText = this.defaultText;
            
            if (!isfocus) {
                if (!val && val != defaultText) {
                    this.inputor.val(this.val = defaultText);
                }
            } else {
                if (val == defaultText) {
                    this.inputor.val(this.val = '');
                }
            }
        },
        
        onblur : function(e){
            this.checkDefault();
            this.focused = FALSE;
        },
        
        onchange : $.noop,
        
        checkVal : function(){
            var delay = this.checkDelay;
            var self = this;
            
            function delayCheck() {
                self.checkTimer = null;
                var val = self.inputor.val();
                self.valTrim && ( val = $.trim(val) );
                if (val !== self.val || self.unChange) {
                    self.onchange(val);
                    self.val = val;
                }
            }

            if (delay) {
                    this.checkTimer && win.clearTimeout(this.checkTimer);
                    this.checkTimer = win.setTimeout(delayCheck, delay);
            } else {
                delayCheck();
            }
            
        },
        
        //防止点击输入框时自动关闭
        onmousedown : function(e) {
			e.stopPropagation();
/*             if (this.focused) {
                return false;
            } */
        },
        
        init : function(){
            proto.init.apply(this, arguments);
            
            this.val = this.inputor.val();
            
            //初始化，绑定事件
            this.inputor.bind({
                keyup : Util.getBind(this, 'onkeyup'),
                focus : Util.getBind(this, 'onfocus'),
                click : Util.getBind(this, 'onclick'),
                blur : Util.getBind(this, 'onblur'),
                keydown : Util.getBind(this, 'onkeydown'),
                mousedown : Util.getBind(this, 'onmousedown') 
            });
        },
        
        onmouseover : $.noop,
        onmouseout : $.noop,
        
        onViewReady : function(){
            proto.onViewReady.call(this);
            this.jq().bind({
                mouseover : Util.getBind(this, 'onmouseover'),
                mouseout : Util.getBind(this, 'onmouseout')
            });
        }
    }
    
}));


mod.atWho = X.reg('atWho',Util.create(ui.Layer,{
    view: 'atwho',
    now : 0,
    length :0,
    key : '',
    atWhoShow : 0,
//    cache:[],
    oldXhr : null,
    //@字符所在位置
    flagAt : null,
    
    //是否正在使用
    useable : 1,
    
    isFocus: false,
    
    //设置或者取得使用状态
    run : function(makeuse) {
        if (makeuse === undefined) 
            return this.useable;
            
        this.useable = makeuse;
    },
    
    onViewReady : function(){
        var self = this;

        this.Inputor        
        .bind('keyup', function(e){
            switch (e.keyCode) {
                case 38:
                case 40:
                    return false;
                break;
                default:
                    self.showWho(e);
            }
        })
        .bind('keydown',function(e){
            return self.onkeydown(e);
        })
        
        .bind('focus', function(e) {
            self.isFocus = true;
            //self.showWho(e);
        })

        .bind('click' ,function(e){
            self.showWho(e);
        })

        .bind('blur', function() {
            self.isFocus = false;
                        
             if(self.atWhoShow){
             this.TimeoutID=setTimeout(function(){
                    self.display(false);
                    self.atWhoShow = false;},150);
             }
        });

        this.jq('#mainUL').click(function(e){
            if(e.target.tagName == 'LI'){
                self.choose();
            }
        });
        this.jq('#mainUL').mousemove(function(e){
            if(e.target.tagName == 'LI'){
                $(this).find('li:eq('+ self.now +')').removeClass('cur');
                $(e.target).addClass('cur');
                self.now = $(this).find('li').index(e.target);
            }
        });
    },
    //延时计时器
    //trigTimer : null,
    
    //延时时长 (ms)
    //delay : 100,
    
    showWho:function(e){
        if (!this.run()) return;
        
        var key=this.getKey(this.Inputor[0]);
        if (__debug) console.log(key);
        this.txtobj = key;
        if( key ){
            //if(key.text == this.key ) return;
            this.reload( key.text );
        } else {
            this.key = "";
            this.length= 0 ;
            this.display(false);
        }
    },
    onkeydown : function(e){
        if (!this.atWhoShow){
            return;
        }
        
        switch(e.keyCode){
            //上
            case 38 : 
                if(this.now == 0) return false;
                //this.jq('#mainUL li:eq('+( this.now-1 )+')').addClass('cur');
                this.jq('#mainUL li:eq('+ this.now +')')
                    .removeClass('cur')
                    .prev()
                    .addClass('cur');
                this.now--;
                return false;
                break;
            //下
            case 40 : 
                if(this.now+1 == this.length) return false;
                //this.jq('#mainUL li:eq('+( this.now+1 )+')').addClass('cur');
                this.jq('#mainUL li:eq('+ this.now +')')
                    .removeClass('cur')
                    .next()
                    .addClass('cur');
                this.now++;
                return false;
                break;
            case 13 :
                if(this.length != 0){
                    this.choose();
                    this.display(false);
                }
                return false;
                break;
            default :return true;
        }
    },
    
    //选取一个数据内容
    choose : function(idx) {
        var inputor = this.Inputor,
            selHolder = inputor.data('xwb_selholder'),
            idx = idx || this.now,
            key = this.key,
            rows = this.cache(key);
        if (!rows || !rows.length) return;
        
        var data = rows[idx],
            nickname = this.format(data),
            txtobj = this.txtobj;
        
        this.run(0);
        if( selHolder ){
            selHolder.replaceString(nickname, txtobj.form, txtobj.to);
        } else {
            this.Inputor.val(Util.stringReplace(inputor.val(), nickname,txtobj.form, txtobj.to))
            Util.setCursor(inputor[0] , txtobj.form + nickname.length )
        }
        
        this.afterChoose(data);
        
        this.run(1);
    },
    
    //选中后的动作
    afterChoose : $.noop,
    
    //转换格式
    format : function(row) {
        return row.nickname + ' ';
    },
    
    //搜索关键字
    getKey:function(elem,val){
        var now = Util.getCursorPos(elem),
            val = elem.value,
            nowchar = val.substring(now-1,now),
            text = "";
        if( this.noAt === true ) {
            if(val.length !== 0){
                this.flagAt = 0;
                return {text:val,form:0,to:val.length};
            } else {
                return false;
            }
        }
        if(nowchar == ' ' || nowchar == '@' )     return false;
        for(var i=now;i>0;i--){
            if(val.substring(i,i-1) == ' ') return false; //搜索中途遇到空格终止搜索
            if(val.substring(i,i-1) == '@'){ //遇到@确认关键字
                text = val.substring(i,now);
                if(val.length > now){  //如果现在的光标不在最后那么我们延伸关键字（到下一空格是不是我们选择出来的）
                    for(var j=now+1;j<=val.length;j++){
                        if(val.substring(j,j-1) == ' ' || j == val.length){
                            var key = val.substring(i,val.substring(j,j-1) == ' ' ? j-1 : j );
                            $(this.data).each(function(){
                                if(key == this.nickname){
                                    now = j;
                                }
                            })
                        }
                    }
                }
                
                this.flagAt = i;
                if(text.length > 20 ) return false;
                return {text:text,form:i,to:now};
            }
        }    
        return false;
        
    },
    
    //调整浮层位置
    rePosition : function() {
        var offset = Util.getCursorOffset(this.Inputor, this.flagAt-1);
        if (offset) {
            var ipOffset = this.Inputor.offset();
            var st = this.Inputor.scrollTop();
            
            var line_h = parseInt($(this.Inputor).css('lineHeight'));

            if (isNaN(line_h)) {
                line_h = 20;
            }
            
            //scrollTop 偏移量
            var stOffset = line_h - st;
            
            this.jq().css({
                top : ipOffset.top + offset.top + stOffset,
                left : ipOffset.left + offset.left
            });
        }
        
        return this;
    },
    
    onResize : $.noop,
    
    //显示前调整位置
    beforeShow : function() {
        this.rePosition();
        ui.Layer.prototype.beforeShow.apply(this, arguments);
    },
    
    //显示后监听resize事件
    afterShow : function() {
        if (__debug) {
            console.log('atWho: listen resize event.');
        }
        this.onResize = Util.bind(this.rePosition, this);
        $(win).resize(this.onResize);
        
        ui.Layer.prototype.beforeShow.apply(this, arguments);
        
        this.atWhoShow = 1;
    },
    
    //隐藏后取消监听resize事件
    afterHide : function() {
        if (__debug) {
            console.log('atWho: unlisten resize event.');
        }
        
        $(win).unbind('resize', this.onResize);
        
        this.atWhoShow = 0;
        ui.Layer.prototype.afterHide.apply(this, arguments);
    },
    
    //对关键字加黑
    highlight : function(txt, search) {
        return txt.replace(search, '<b>' + search + '</b>');
    },
    
    //显示用户列表
    showUser : function(userlist) {
        this.length = userlist.length;
        this.data = userlist;
        
        if (!userlist || !userlist.length) {
            return this.display(0);
        }
        
        var ul = [], highlight = this.highlight ,self = this;
        
        $.each(userlist, function(i, usr){
            var remark = usr.remark,
                nickname = usr.nickname,
                eleHtml = '<li>' + highlight(usr.nickname , self.key);
                
            if (remark) {
                eleHtml = eleHtml + '(' + highlight(remark , self.key) + ')';
            }
            
            eleHtml += '</li>';

            ul.push(eleHtml);
        });
        
        this.now = 0
        
        this.jq('#mainUL')
            .html(ul.join(''))
            .find(':first-child')
            .addClass('cur');
            
        if (this.display()) {
            this.rePosition();
        }
        this.display(1);
    },
    
    //查询完成后回调
    loaded : function(e) {
        if (e.isOk()) {
            var rst = e.getData();
            this.cache(rst.key, rst.data);
            if (this.isFocus) {
                this.showUser(rst.data);
            }
        }
    },
    
    //请求关键字
    reload : function(key){
        this.key = key;
        var rst= this.cache(this.key);
        if (__debug) console.log('seach:',key,'return:',rst,'cache:',mod.atWho.cache);
        if( rst !== undefined ) { 
            this.showUser(rst);
        } else { 
            if( this.oldXhr && (this.oldXhr.readyState !== 4 || this.oldXhr.status !== 200) )this.oldXhr.abort();
			
            this.oldXhr = Req.selectUser(this.url || Req.apiUrl('action','getAtUsers'),{ k:this.key },Util.getBind(this,'loaded'));
			//Req.q(this.url || Req.apiUrl('action','getAtUsers'),{ k:this.key },Util.getBind(this,'loaded'));
        }
    },
    //根据关键字搜索或存储缓存
    cache : function(key, data){
        if (data === undefined)
            return mod.atWho.cache[key];
            
        mod.atWho.cache[key] = data;
    }
}));
//atWho查询缓存
mod.atWho.cache = {};
/**
 * @class Xwb.mod.PostBase
 * 发布微博功能基类，
 * 所有属性和方法被复制到子类，子类初始化后调用{@link #initEx}方法初始化基类。
 */

/**
 * @cfg {Function} beforeSend 发布微博前回调，回调参数为 posebase.beforeSend(text, this.uploadPic, requestParams)，如果需更改text内容，请在beforeSend返回text内容。
 * beforeSend 返回 false时取消发布。
 * 可在requestParams里丰富提交参数，也可以在{@link #param}属性增减提交参数，它们是同一对象。
 */
/**
 * @cfg {Object} param，可指定该属性设置每次发布微博时的提交参数，初始化后可往该属性动态添加或减少提交参数。
 */
mod.PostBase = {
    
    actionMgr : true,
	
	exceedCS : 'tips-on',
	
	canAtWho : false,
    
    //输入框内的默认文字
    defText : '',

    initEx : function(){
        var jqInputor = this.jqInputor = this.jq('#xwb_inputor');
        var jqSendBtn = this.jqSendBtn = this.jq('#xwb_send_btn');
		var jqInputorParent = this.jq(this.focusEl||'#focusEl');
        
        this.jqWarn      = this.jq('#xwb_word_cal');
        this.jqImgFile   = this.jq('#xwb_img_file');
        this.jqBtnImg    = this.jq('#xwb_btn_img');
        this.jqUploadTip = this.jq('#xwb_upload_tip');
        this.jqPhotoName = this.jq('#xwb_photo_name');
        this.jqForm      = this.jq('#xwb_post_form');
        this.$uploadBtn  = this.jq('#uploadBtn');
        
        this.selectionHolder = X.use('SelectionHolder', {elem:this.jqInputor[0]});
        
        var self = this;
        
        this.jqImgFile.change(function(e){
            self.onImgFileChange(e);
        });
        
        if( this.btnHoverCS )
            jqSendBtn.hover(
                function(){ jqSendBtn.addClass(self.btnHoverCS); }, 
                function(){ jqSendBtn.removeClass(self.btnHoverCS); }
            );
		if(this.canAtWho)
			this.atWho = X.use('atWho',{
				appendTo:doc.body,
				Inputor : jqInputor,
				autoRender : true
			});
        
        jqInputor
        .bind('keyup', function(e){
            self.onInputorKeyup(e);
        })
		.bind('focus', function(e) {
			jqInputorParent.addClass('post-focus');
		})
		.bind('blur', function() {
			jqInputorParent.removeClass('post-focus');
		});
    },

    getUploader : function(){
        if(!this.uploader)
            this.uploader = X.use('Uploader', {
                form:this.jqForm[0], 
                action : Req.mkUrl('api/weibo/action', 'upload_pic'),
                onload:Util.getBind(this, 'onUploadLoad')
            });
        return this.uploader;
    },
    
    reset : function(){
        this.jqUploadTip.cssDisplay(false);
        this.jqPhotoName.cssDisplay(false);
        //this.jqBtnImg.cssDisplay(true);
        //this.jqForm.cssDisplay(true);
        this.$uploadBtn.cssDisplay(1);
        this.selectionHolder.setText(this.defText);
        this.jqForm.length && this.jqForm[0].reset();
        this.uploadPic = false;
        this.checkText();
        this.sending = false;
        return this;
    },
    
    onactiontrig : function(e){
        switch(e.data.e){
            case 'sd' :
                this.post();
                break;
            case 'ic' :
                X.use('emotion')
                 .setSelectionHolder( this.selectionHolder , this.checkText, this)
                 .showAt(e.src);
            break;
            case 'vd' :
                 X.use('videoBox')
                  .showAt(e.src, Util.getBind(this, 'onBoxTextReturn'));
            break;
            case 'ms' :
                  X.use('musicBox')
                   .showAt(e.src, Util.getBind(this, 'onBoxTextReturn'));
            break;
			case 'con' :
				e.stopPropagation(false);
			break;
			
			case 'c' :
				this.display(0);
			break;
            case 'tp' :
                this.insertTopic();
            break;
            // 删除已上传图片
            case 'dlp':
                this.uploadPic = false;
                //this.jqBtnImg.cssDisplay(true);
                //this.jqForm.cssDisplay(true);
                this.$uploadBtn.cssDisplay(1);
                this.jqPhotoName.cssDisplay(false);
                this.jqInputor.focus();
                break;
			case 'bs' :
				this.bindSave && this.bindSave();
			break;
        }
    },
    
    onBoxTextReturn : function(text){
        if(text)
            this.selectionHolder.insertText(text);
        this.checkText();
    },
    
    checkText : function(){
        var v = $.trim( this.jqInputor.val() );
        var left = Util.calWbText(v);
        if (left >= 0)
            this.jqWarn.html( left );
        else
            this.jqWarn.html(left);
            
        this.jqWarn.checkClass(this.exceedCS,left<0);     
        return left>=0 && v;
    },
    
    checkImg : function(fileName){
		var pieces = fileName.split('.');
		return pieces.length && $.inArray(pieces.pop().toLowerCase(), ['jpg', 'png', 'gif','jpeg']) !== -1;
    },
    
    onInputorKeyup : function(e){
        if(this.checkText()){
            // ctrl + enter post
            if(e.ctrlKey && ( e.which == 13||e.which == 10 ))
                this.post();
        }
    },
    
    TOPIC_TIP : getText('请在这里输入自定义话题'),
    
    insertTopic : function(topic){
        if(!topic)
            topic = this.TOPIC_TIP;
        var inputor = this.jqInputor[0];
        var hasCustomTopic = new RegExp('#'+this.TOPIC_TIP+'#').test(inputor.value);
        var text = topic, start=0,end=0;
        
        inputor.focus();
        
        if (document.selection) {
            var cr = document.selection.createRange();
            //获取选中的文本
            text = cr.text || topic;
        
            //内容有默认主题，且没选中文本
            if (text == topic && hasCustomTopic) {
                start = RegExp.leftContext.length + 1;
                end   =   topic.length;
            }
            //内容没有默认主题，且没选中文本
            else if(text == topic) {
                cr.text = '#' + topic + '#';
                start = inputor.value.indexOf('#' + topic + '#') + 1;
                end   = topic.length;
            }
            //有选中文本
            else {
                cr.text = '#' + text + '#';
            }
        
            if (text == topic) {
                cr = inputor.createTextRange();
                cr.collapse();
                cr.moveStart('character', start);
                cr.moveEnd('character', end);
            }
        
            cr.select();
        }
        else if (inputor.selectionStart || inputor.selectionStart == '0') {
            start = inputor.selectionStart;
            end = inputor.selectionEnd;
        
            //获取选中的文本
            if (start != end) {
                text = inputor.value.substring(start, end);
            }
        
            //内容有默认主题，且没选中文本
            if (hasCustomTopic && text == topic) {
                start = RegExp.leftContext.length + 1;
                end = start + text.length;
            }
            //内容没有默认主题，且没选中文本
            else if (text == topic) {
                inputor.value = inputor.value.substring(0, start) + '#' + text + '#' + inputor.value.substring(end, inputor.value.length);
                start++;
                end = start + text.length;
            }
            //有选中文本
            else {
                inputor.value = inputor.value.substring(0, start) + '#' + text + '#' + inputor.value.substring(end, inputor.value.length);
                end = start = start + text.length + 2;
            }
        
            //设置选中范
            inputor.selectionStart = start;
            inputor.selectionEnd = end;
        }
        else {
            inputor.value += '#' + text + '#';
        }
        
        this.checkText();
        this.selectionHolder.saveSpot();
    },
    
    post : function(){
        var text = this.checkText();
        
        if(!text){
            this.jqInputor.focus();
            return;
        }

        if( this.getUploader().isLoading() ){
            MB.tipWarn( getText('图片正在上传，请稍候..') );
            return;
        }
        
        if(this.sending){
            MB.tipWarn( getText('正在发布,请稍候..') );
            return;
        }
        
        var param = $.extend({}, this.getParam());
        
        if(this.beforeSend){
            var ret = this.beforeSend(text, this.uploadPic, param);
            if(ret === false)
                return;
            text = ret || text;
        }
        
        this.sending = true;
        // 传递当前页面标识_route，以返回不同HTML内容
        Req.post(text, Util.getBind(this, 'onSendLoad'), this.uploadPic, { data : param});
    },
    
    /**
     * 返回发布微博时额外的提交参数。
     * @private
     */
    getParam : function(){
        var param = this.param;
        if(!param)
            param = this.param = {};
        if(!param._route)
            param._route = X.getModule();
        return param;
    },
    
    onImgFileChange : function(){
        var jq = this.jqImgFile;
        var fn = jq.val(), self = this;
        
        this.uploadPic = null;
        
        if( !fn || !this.checkImg(fn) ){
            this.jqForm[0].reset();
            MB.alert('', getText('只支持{0}格式的图片。', 'jpg、png、gif') , function(){
                self.jqInputor.focus();
            });
            return ;
        }
        this.jq('#xwb_upload_tip').cssDisplay(true);
        //this.jqForm.cssDisplay(false);
        //this.jqBtnImg.cssDisplay(false);
        this.$uploadBtn.cssDisplay(0);
        // add submit disabled class
	    this.getUploader().upload();
    },
    
    onUploadLoad : function(e){
		if(typeof e != 'object'){
			MB.alert('提示', "上传失败!");	
		}	
        else if( e.isOk() ){
            var data = e.getData();
            this.uploadPic = data.msg;
            this.jqPhotoName.html(Util.getFileName(this.jqImgFile.val(), 10) + T.get('UploadImgBtn') );
            this.jqPhotoName.cssDisplay(true);
            !$.trim(this.jqInputor.val()) && this.selectionHolder.setText( getText('分享图片') );
            this.checkText();
        }else {
            MB.alert('', e.getMsg( getText('图片发布') ) );
            //this.jqBtnImg.cssDisplay(true);
            //this.jqForm.cssDisplay(true);
            this.$uploadBtn.cssDisplay(1);
        }
        this.jqUploadTip.cssDisplay(false);
        this.jqForm[0].reset();
        this.jqInputor.focus();
        // remove disabled class
    },
    
    // 参数二为可选
    onSendLoad : function( e , callback){
        var jqInputor = this.jqInputor;
        if(e.isOk() || e.getCode() == '30000'){
		
            if(! this.jqMask ){
                this.jqMask  = { succ: this.jq('#xwb_succ_mask'),veri:this.jq('#xwb_veri_mask') };
                this.jqMaskPt = this.jqMask.succ.parent();
            }
            
			var jqMask = e.isOk() ? this.jqMask.succ : this.jqMask.veri;
			
            jqMask.cssDisplay(true)
                  .show()
                  .appendTo(this.jqMaskPt);

            jqInputor.focus();
            var self = this;
            jqMask.fadeOut(1800, function(){
                // 修正IE下滤镜使得层不会隐藏的BUG，
                // 如果不移除，则不会隐藏
                jqMask.remove();
                jqMask[0].style.filter = null;
                self.reset();
                callback && callback.call(self, e);
            });
            
            // 发送新微博事件
            // X.fire('wb.create', e.getData(), e);
        }else {
			if(e.getCode() == '30000'){
				MB.tipWarn( getText('信息已进入审核中') ,function(){
					Util.focusEnd(jqInputor[0]);
				});
			} else {
				MB.alert('', e.getMsg(), function(){
					Util.focusEnd(jqInputor[0]);
				});
			}
            this.sending = false;
        }
    }
};

/**
 * @class Xwb.mod.postBox
 * 发布微博弹出框
 * @extends Xwb.ui.Box
 * @extends Xwb.mod.PostBase
 * @singleton
 */
 
// 这写法是调用时才实例化
X.reg('postBox', function(cfg){
    
    var inst = $.extend({}, mod.PostBase);
    
    $.extend(inst, {
		autoCenter:true,
        closeable : true,
        appendTo : doc.body,
        
        mask : true,
        
        cs : 'win-share',
        
        contentHtml : 'PostBoxContent' ,
		
		FriendLoad : false,

        onViewReady : function(v){
			this.initEx();
        },
		
		initFriend:function(){
			if(this.showFriend && !this.FriendLoad){
				var self = this,friendItem = this.jq('div.friend-item');
				friendItem.append($(X.ax.Tpl.parse('Loading')));
				Req.q(Req.mkUrl('api/spots/action','getFriends'),{},function(r){
					if(r.isOk()){
						var ul = friendItem.find('ul');
						$(r.getData()).each(function(){
							ul.append('<li title="'+this.screen_name+'"><a href="#"><img src="'+this.profile_image_url+'"></a></li>');
						});
						ul.find('li').click(function(){
							$(this).toggleClass('checked');
							self.updataContent();
							self.checkText();
							return false;
						});
						friendItem.find("div.loading").remove();
						self.FriendLoad = true;
					}
				});
			}
		},
		
		updataContent : function(){
			var nameArr=[];
			this.jq('div.friend-item').find('li.checked').each(function(){
				nameArr.push('@' + $(this).attr('title'));
			});
			this.selectionHolder.setText(this.m + nameArr.join(' '));
		},
		
		reset:function(){
			this.jq('div.friend-item').find('li.checked').removeClass('checked');
			return mod.PostBase.reset.call(this);
		},
        
        onbuttonclick : function(bid){
            if( bid == 'ok'){
                this.post();
                // 取消对话框关闭
                return false;
            }
        },
        
        // override
        
        onSendLoad : function(e){
            mod.PostBase.onSendLoad.call(this, e, function(e){
                if( e.isOk()){
                    this.close();
                    // fix bug#334,IE下光标隐藏后不消失
                    this.jqInputor[0].blur();
                }          
            });
        }
    },cfg);
    
    inst = X.use('Box', inst);
    
    X.reg('postBox', inst, true);
    
    return inst;
});

/**
 * @class Xwb.mod.WeiboList
 * 微博列表UI
 * @extends Xwb.ui.Base
 */
mod.WeiboList = X.reg('WeiboList', Util.create(Base, {
    
    ctNode : '#xwb_weibo_list_ct',
    
    innerViewReady : function(v){
        base.innerViewReady.call(this, v);
        this.jqCt = this.jq(this.ctNode);
        // unsyncList属性置为真时不监听微博更新列表
        if(this.syncList){
            X.on('api.update', this.onWbCreate, this);
            // 转发时目前后台PHP未对返回的头像进行处理
            // X.on('api.repost', this.onWbCreate, this);
        }
    },
    
    // 插入到weibo list
    // item = {data:{wbid:wbData}, html:html}
    // 出于性能考虑，该UI类只维护追加新微博HTML内容到列表，
    // 不维护删除某此微博内容，删除列表中某条微博内容由其它功能自己实现。
    // 不排除以后根据需要实现该功能。
    onWbCreate : function(e){
        var retData = e.getData();
        var wbsData = retData.data;
        // 这个返回的数据结构设计的很奇怪
        for(var id in wbsData){
            this.append(id, wbsData[id], retData.html);
            break;
        }
    },
    
    /**
     * 追加微博到列表。参数config可选属性如下：<br/>
     * {Boolean} noSlide 是否有动画效果<br/>
     * {Boolean} append prepend OR append<br/>
     * {Boolean} cancelParseShortlink<br/>
     * @param {String} weiboId
     * @param {Object} weiboData
     * @param {String} weiboHtml
     * @param {Object} config
     * @return {jQuery} item, 无html时返回空
     */
    append : function(id, item, html, cfg){
        this.item(id, item);
        cfg = cfg || {};
        if(html){
            html = $.trim(html);
            var self = this;
            var jq = $(html);
            
            if(!cfg.append)
                jq.prependTo(this.jqCt);
            else
                jq.appendTo(this.jqCt);
            /*
            if(!cfg.noSlide){
              jq.hide()
                .fadeIn(1000, function(){
                   if(!cfg.cancelParseShortlink){
                       var obj = {};
                       obj[id] = item;
                       X.mod.shortlink.from(obj, function(list){
                           X.mod.shortlink.renderWeiboShortlink(jq, list[id], list[id].shortlinks);
                       });
                    }
                });
            }else {
                   if(!cfg.cancelParseShortlink){
                       var obj = {};
                       obj[id] = item;
                       X.mod.shortlink.from(obj, function(list){
                           X.mod.shortlink.renderWeiboShortlink(jq, list[id], list[id].shortlinks);
                       });
                    }
            }
            */
            
            return jq;
        }
    },
    
    batchAppend : function(list, htmls, append){
        /*
        var items = [];
        var cfg = {noSlide:true, append:append,cancelParseShortlink:true};
        for(var id in list){
            items.push( id, this.append(id, list[id], htmls[id], cfg) );
        }
        X.mod.shortlink.from(list, function(linkedList){
            for(var i=0,len=items.length;i<len;i+=2){
                var id = items[i];
                var jq = items[i+1];
                // 有可能无HTML输出
                if(jq)
                    X.mod.shortlink.renderWeiboShortlink(jq, linkedList[id], linkedList[id].shortlinks);
            }
        });
        */
    },
    
    item : function(id, v){
        if( v === undefined )
            return getWb(id);
        setWb(id, v);
    }
}));

/**
 * @class Xwb.mod.SearchEntry
 * 搜索框
 * @extends Xwb.ui.Base
 */
mod.SearchEntry = X.reg('SearchEntry', Util.create(Base, {
    focusText : getText('搜微博/找人'),
    focusCs   : 'search-box-focus',
    // 30个字节
    maxLen    : 30,
    
    innerViewReady : function(v){
        base.innerViewReady.call(this, v);
        var jqInputor = this.jqInputor = this.jq('#xwb_inputor'),
            jqTrigBtn = this.jq('#xwb_trig'),
            self = this;

        jqTrigBtn.click(function(){
            return self.submit();
        });
        
        
        jqInputor.keydown(function(e){
            var kc = e.keyCode;
            if(kc===13)
                self.submit();
        });
        
        if(this.focusText)
            jqInputor.focusText(this.focusText, this.focusCs, this.getView());
    },

 
    submit : function(){
        var kw = $.trim(this.jqInputor.val());
        if(kw == this.focusText)
            kw = '';
        if(!kw){
            this.jqInputor.focus();
        }else {
            var kw = encodeURIComponent( Util.byteCut(kw, this.maxLen) ),
                url = Req.mkUrl('search','', 'k=' + kw);
            win.location.href = url;
        }
    }
}));

/**
 * @class Xwb.mod.authLogin
 * SINA帐号与本站帐号登录相关的处理
 * @singleton
 */
mod.authLogin = { 
	forwardUrl: null,   //登录后指定跳转链接
    /**
     * 利用window.open方法弹出auth登录框
     * @param {String} type 第三方登录类型sina、qq、renren
	 * @param {String} isBind 是否是绑定帐号 or 第三方登录
	 * @param {String} url 指定登录成功后的跳转链接
     */
	open2 : function( type , isBind, url ){
		url ? this.forwardUrl = url : this.forwardUrl = '';
	    var logWin = this.logWin;
		
        if(logWin && !logWin.closed)
            logWin.focus();
	    else {
		    var openWinsH = { 'sina': 380, 'qq': 580, 'renren': 340 },
			    h = openWinsH[ type ] || 440;  //根据type设置窗口高度
			this.type = type;
			this.logWin = win.open(
				isBind ? Req.mkUrl('setting','bind')+"&type="+type : Req.mkUrl('account','login')+"&type="+type, 
				"logWin",
				"resizable=1,location=0,status=0,scrollbars=0,width=570,height="+h+""
			);
			if(!this.bindLoginCallback){
			    var prefix = isBind ? 'bind' : 'login';
				win[  prefix + '3PartSucc'] = Util.bind(this.onPopupCallback, this);
		    	win[  prefix + '3PartFail'] = Util.bind(this.logFail, this);
				this.bindLoginCallback = true;
			}
        }
	},
	
	trdFllow : function( type , url ){
		url ? this.forwardUrl = url : this.forwardUrl = '';
	    var logWin = this.logWin;
        if(logWin && !logWin.closed)
            logWin.focus();
	    else {
		    var openWinsH = { 'sina': 380, 'qq': 580, 'renren': 340 },
			    h = openWinsH[ type ] || 440;  //根据type设置窗口高度
			this.type = type;
			this.logWin = win.open(
				Req.mkUrl('account','friConnect'),
				"logWin",
				"resizable=1,location=0,status=0,scrollbars=0,width=570,height="+h+""
			);
			if(!this.bindFlCallback){
				win['friConnectSucc'] = Util.bind(this.onPopupCallback, this);
		    	win['friConnectFail'] = Util.bind(this.logFail, this);
				this.bindFlCallback = true;
			}
        }
	},
	
	
    // private
    // 当第三方验证通过后，
    // 跳转到PHP统一页面(account.oauthCallback)，
    // 再由该页面输出一段脚本
    // 回调opener窗口的 login3PartSucc 方法
    onPopupCallback : function( redirect ){
	    this.logWin.close();
		if( this.forwardUrl ){
			location.href = this.forwardUrl
		}
		else if( X.getModule() === 'account.register' || X.getModule() === 'account.login' ){
		   location.href =  redirect || "/";
		}else {
		    var reloadUrl = X.use('loginBox').beClickedLink;　
			if( reloadUrl && !/account.login/.test(reloadUrl) ) {
			    if( reloadUrl.indexOf('#') > 0 )  //去掉reloadUrl的hash值
				    reloadUrl = reloadUrl.substring(0, reloadUrl.indexOf('#'));
			    var curl = location.href.replace(/&?_=\d+/g,''),
				    urlHash = curl.indexOf('#') > 0 ? curl.substring(curl.indexOf('#')) : '',
					rndSuffix = reloadUrl.indexOf('?') > 0 ? '&_=' + new Date().getTime() : '?_=' + new Date().getTime();
    			location.href = reloadUrl + rndSuffix + urlHash;
			}else location.reload(1);   //页自身刷新
		}
    },
	logFail : function( errcode ){
		this.logWin.close();
		if( errcode == '417407' )   //提示:第三方帐号已绑定
		    MB.alert("提示",Req.ERRORMAP[ errcode ] );
		else MB.alert("提示",Req.ERRORMAP[ errcode ] || "绑定失败。未知的错误码: " + errcode );
		return false;
	}
};
/**
 * @class Xwb.mod.loginBox
 * 登录框
 * @extends Xwb.ui.Box
 * @singleton
 */
X.reg('loginBox', function( cfg ){
	var inst1 = X.use('Box', {
		contentHtml : 'loginBox',
		cs : 'win-login win-fixed',
		title : '登录自游网旅游社区',
		appendTo : doc.body,
		closeable : TRUE,
		mask: TRUE,
		contextable: TRUE,
		onViewReady: function() {
		    var self = this, form = this.jq("form"), pwd = form.find('#pwd'), password = form.find('#g_password');
 			Xwb.use('Validator', {
     			form: form,
     			trigger : this.jq('#btnLogin'),
     			onsuccess : function(data, next){
					Req.postReq( Req.mkUrl('jsApi/accountApi','login'), $(this.form).serialize(), function(e){
						if( e.isOk() ){
		    				var reloadUrl = X.use('loginBox').beClickedLink;　
							if( reloadUrl && !/account.login/.test(reloadUrl) ) {
			    				if( reloadUrl.indexOf('#') > 0 )  //去掉reloadUrl的hash值
				   					 reloadUrl = reloadUrl.substring(0, reloadUrl.indexOf('#'));
			    				var curl = location.href.replace(/&?_=\d+/g,''),
				    				urlHash = curl.indexOf('#') > 0 ? curl.substring(curl.indexOf('#')) : '',
									rndSuffix = reloadUrl.indexOf('?') > 0 ? '&_=' + new Date().getTime() : '?_=' + new Date().getTime();
    								location.href = reloadUrl + rndSuffix + urlHash;
							}else location.reload(1);   //页自身刷新
                        }
						else{							
							if(e.getCode() == '1417005'){
								self.display(0);
								MB.alert('',e.getMsg());								
							}else
								self.jq("#_tips").html( '<span>'+e.getMsg()+'</span><i></i>' || "未知错误" ).removeClass('hidden');
						}
						next();
					});
         			return false; // 非FORM提交返回false
     			}
 			});
			
			pwd.focus(function(e){
				pwd.cssDisplay(0);
				password.cssDisplay(1).focus();				
			});
			password.blur(function(e){
				if(Util.trim(this.value) == ''){
					password.cssDisplay(0);
					pwd.cssDisplay(1);
				}
			}); 
			
			setTimeout(function(){self.jq().find("input:first").focus()},1);
		},
		beforeShow: function(){
			//Xwb.ui.Box.prototype.beforeShow.call(this);
		    if( X.use('loginBox2').isShow ) {
			    X.use('loginBox2').graduallyShow(0);
			}
			this.jq("#_tips").cssDisplay(0);
		},
		onclose: function(){
		    this.beClickedLink = '';
		}
	});
	// override function -> object
	X.reg('loginBox', inst1, true);

	return inst1;
});
/**
 * 右侧顶部登录框 
 * @extends Xwb.ui.Box
 * @singleton
 */
X.reg('loginBox2', function(){
	var inst2 = X.use('Box', {
		contentHtml : 'loginBox2',
		cs : 'win-notice win-login-s2',
		appendTo : doc.body,
		closeable : true,
		reflowTime: 300000, //300秒(5分钟)后重现
		sceduler: null,
		retrieve_password : Req.mkUrl('account','retrieve_password'),
		scrollShow: true, //滚动显示
		isShow: false,
		beforeShow: function(){
		   clearTimeout(this.sceduler);
		},
		onViewReady: function() {
		    var self = this, form = this.jq("form"), pwd = form.find('#pwd'), password = form.find('#password');
/*  			Xwb.use('Validator', {
     			form: form,
     			trigger : this.jq('#btnLogin'),
				onerror : function(data, next){
					if(data.name == 'password'){
						pwd.cssDisplay(0);
						password.cssDisplay(1);	
					}
					X.ax.ValidationMgr.prototype.onerror.apply(this, arguments);
				},
     			onsuccess : function(data, next){
					Req.postReq( Req.mkUrl('jsApi/accountApi','login'), $(this.form).serialize(), function(e){
						e.isOk() ? location.reload(1) : self.jq("#tips").html( '<span>'+e.getError()+'</span><i></i>' || "未知错误" ).removeClass('hidden');
						next();
					});
         			return false; // 非FORM提交返回false
     			}
 			});
			pwd.focus(function(e){
				pwd.cssDisplay(0);
				password.cssDisplay(1).focus();				
			});
			password.blur(function(e){
				if(Util.trim(this.value) == ''){
					password.cssDisplay(0);
					pwd.cssDisplay(1);
				}
			}); */
		},
		close: function(){
			var self = this;
			self.scrollShow = false;
		    self.sceduler = setTimeout( function(){
			    self.graduallyShow(1);
				self.scrollShow = true;
			}, self.reflowTime );
		    this.graduallyShow(0);
		},
		graduallyShow: function( b ){
		    if( this.isShow == b )
			    return false;

			this.isShow = b
			var ov = b ? 1 : 0;

			var jq = this.jq();
            if ($.browser.msie && $.browser.version < 9 ) {
                jq.cssDisplay(b);
            } else {
			    if( jq.hasClass('hidden') )
			        jq.css({'opacity': 0}).removeClass('hidden');
			    
			    jq.animate({'opacity': ov},'slow', function(){
			        jq.cssDisplay(ov); 
			    });
            }
		}
	});
	// override function -> object
	X.reg('loginBox2', inst2, true);

	return inst2;
});

/**
 * 数据上报
 * @method report
 * @member Xwb
 */
X.report = (function() {
	//上报地址
	var url = 'http://beacon.ziyou.com/a.gif',

	//图片对象
		img,

		//用户ID，如果未登录，生成一个随机ID
		uid,

		//初始化上报参数
		reqOpt = {
			//pjt: 'ziyou',
			xt: 'stay'
		};

	//生成随机ID
	function genId(num) {
		var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		var len = str.length;

		var num = num || 16;

		var chars = ['u'], at;
		for (var i = 0 ;i< num ;i++)
		{
			at = Math.ceil(Math.random()*len)-1;
			chars.push(str.charAt(at));
		}

		return chars.join('');
	}

	//取得用户ID
	function getUniqueUid() {
		return getCfg('c_id');

/* 		var        
            cookieName = 'x3w4b',

		    uid = $.cookie(cookieName);

			if (!uid)
			{
				uid = genId();
				$.cookie(cookieName, uid, {
					expires: 90000
				});
			}

		return uid; */
	}

	function report(params) {
        //if (!reqOpt.akey) {
        //    reqOpt.akey = getCfg('akey');
        //}
        
        if (!reqOpt.ver) {
            reqOpt.ver = getCfg('version');
        }
        
		params.random = Math.random();
		params.cid = getUniqueUid();
		//params.akey = X.getCfg('akey');
        params.url = location.href;
        var sinaid = getCfg('uid');
        
        if (sinaid) {
            params.uid = sinaid;
        }

		var opt = $.extend(reqOpt,params);
		
		$.each(opt, function(i, k) {
			opt[i] = encodeURIComponent(k);
		});
		img.src = url + '?data=' + encodeURIComponent($.toJSON(opt));
	}

	//在线时长汇报
	var olReporter = (function() {
		var timer,
			//上报间隔
			interval = 1800000,

			//初始化状态
			inited = false,
				
			bootTime = new Date().getTime(),

			lastTime = 0,
				
			uid;

		function init() {
			if (inited)
			{
				return;
			}

			uid = getUid();

			img = new Image();

			inited = true;
		}

		function doReport(opt) {
			var now = new Date().getTime(),

			params = {
				time: now - (lastTime ? lastTime: bootTime)
			};

/* 			if (!lastTime && document.referrer)
			{
				params.t_id = document.referrer;
			} */
			if(opt) $.extend(params, opt);

			report(params);

			lastTime = now;
		}

		return {
			start: function() {
				init();
                
                //首次上报
                doReport({time:0, referer : document.referrer || ''});
                
				timer = win.setInterval(doReport, interval);
			},

			report: function(opt) {
				!inited && init();
				doReport(opt);
			}
		}
	})();

	return {
		start: function() {
			olReporter.start();
		},

		report: function(opt) {
			olReporter.report(opt);
		}
	}

})();

//景点搜索
X.reg('search', Util.create(Base, function(proto){
return {
    //输入框
    inputor : NULL,
    
    //清除按键
    clear : NULL,
    
    search : null,
    
    autoRender : TRUE,
    
    focusCS : '',
    
    onEnter : NULL,
	
	type : 'spots',
	
	affixfun:$.noop,
    
    //是否捕获点击事件
    catchClick : FALSE,
    
    innerViewReady : function(){

        if (!this.inputor) {
            if (__debug) console.log('error : this.input is null');
            return;
        }
        var objSearch = this;
        //自动完成辅助对象
		this.searchButton = $(this.searchButton);
		this.searchButton.click(function(e){			
			var sthis = $(this);
			e.preventDefault();
			if(this.type == 'spots'){				
				if(sthis.hasClass(objSearch.notNullCS)){
					objSearch.inputor.val(objSearch.defaultText||'搜景点');
					sthis.attr('class','search-btn');
				}
			}else{
				var k = Util.trim(objSearch.inputor.val());
				if(k){
					if(k != objSearch.defaultText)
						location.href = Req.mkUrl('search','',{q:k});
					else
						objSearch.inputor.focus();
				}
			}
		});
		
        if (objSearch.defaultText)
		    objSearch.inputor.val(objSearch.defaultText || '搜景点');
		
		if(objSearch.type == 'total'){//enter到搜索页
			objSearch.inputor.keydown(function(e){
				if(e.keyCode == 13){
					objSearch.enterInput($(objSearch.searchButton));
				}
			});
		}
        var search = this.search = X.use('AutoComplete', function(proto){
            //数据缓存
            var cache = {}, delaySearchTimer;
            return {
                view : objSearch.viewTemp || 'searchSpots' ,
                
				valTrim : true,
				
				cache : [],
                
                inputor : objSearch.inputor,
                
                appendTo : objSearch.getView(),
				
				unChange : objSearch.unChange || false, //输入框获取焦点时是否显示浮层
                
                checkChange: TRUE,
                
                defaultText : objSearch.defaultText == undefined ? '搜景点' : objSearch.defaultText,
				
				outLimit : objSearch.outLimit || '',  //限制输出量
                
                loadXhr : NULL,
                
                clear : NULL,
                
                focusCS : objSearch.focusCS,
				
				onmouseover : objSearch.onmouseover || $.noop,
				
				onmouseout : objSearch.onmouseout || $.noop,
                
                //选中状态的class
                selCls : '',
                
                //延时加载的时间（毫秒）
                loadDelay : 200,
				
				sUrl : objSearch.sUrl || Req.search,//请求地址
                
                //当前选中的
                currentSelected : NULL,
                
                onkeyup : function(e){
					var val = this.valTrim ? $.trim(this.inputor.val()) : this.inputor.val();
					if(val.length){
						objSearch.searchButton.attr('class',objSearch.notNullCS);
					} else{
						objSearch.searchButton.attr('class','search-btn');
					}
                    proto.onkeyup.call(this, e);
                },
                
                reset : function(){
                    this.val = '';
                    this.inputor.val('');
                    
                    this.clear && this.clear.cssDisplay(0);
                },
                
                getData : function(){
                    return this.cache[this.val];
                },
                
                onEnter : objSearch.clickFn || function(e) {
                    var index = this.getIndex(e);
					//var id  = this.getRowId(e);
                    if (index != null) {
                        var data = this.getData();
						if(!data) return;
						var row, spots = data.spots;
                        
                        if (data && spots.length && (r = spots[index])) {
						//if (data.total_number && (r = spots[id])) {
                            if (objSearch.onEnter) {
                                objSearch.onEnter(e, r, spots, index);
								this.display(0);
                            } else {
                                var url;// = Req.mkUrl('spots', '', {name: row.spots, id: row.id, '_r':NULL});
                                if(r.type == 2) {
                                    url = Req.mkUrl('spots', 'citySpots', {pid: r.province_id, id: r.id,cid:r.city_id ,'_r':NULL});
                                } else{
                                    url = Req.mkUrl('spots', 'detail', {name: r.province_name, id: r.id, '_r':NULL});
                                }
                                win.location.href = url;
                            }
                        }
                    }
                },
                
                onfocus : function() {
                    var data = this.getData();
                    if (!this.display() && data && data.length) {
                        this.display(1);
                    }
                    proto.onfocus.call(this);
                    this.focusCS && this.inputor.parent().addClass(this.focusCS);
                },
                
                onblur : function() {
                    proto.onblur.call(this);
                    this.focusCS && this.inputor.parent().removeClass(this.focusCS);
                },
                
                getIndex : function(e) {
					if(e.type == 'keydown'){
						return this.currentSelected ? this.currentSelected.index() : -1;
					} else {
						return $(e.target).closest('li').index();
					}
                },
				
				getRowId : function(e){
					if(e.type == 'click'){
						return $(e.target).attr('rel');
					} else {
						return $(e.target).closest('li').index();
					}
				},

                selectNext : objSearch.selectNext || function(e){
                    var $next;
                    if (this.currentSelected) {
                        $next = this.currentSelected.next();
                    }
                    if (!$next || !$next.length){
                        $next = this.jq((objSearch.children || 'LI')+':first');
                    }
                    this.select($next);
                },
                
                select : function($ele) {
                    var cls = this.selectCls;
                    this.currentSelected && this.currentSelected.removeClass(cls)
                    this.currentSelected = $ele.addClass(cls);
                },
                
                selectPrev : objSearch.selectPrev || function(e) {
                    var $prev;
                    
                    if (this.currentSelected) {
                        $prev = this.currentSelected.prev();
                    }
                    if (!$prev || !$prev.length){
                        $prev = this.jq((objSearch.children || 'LI')+':last');
                    }
                    this.select($prev);
                },
                /*
                onmouseover: function(e){
                    var $target = $(e.target), related = e.relatedTarget;
                    
                    if ($target.attr('tagName') == 'A') {
                        //this.jq('LI').removeClass(this.selectCls);
                        this.select($target.parent());
                    }
                },
                */
                
                onchange : function(val) {
                    if (val) {
                        var data = this.cache[val];
                        if (data)
                            this.showResult(data, val);
                        else {
                            if (delaySearchTimer) {
                                win.clearTimeout(delaySearchTimer);
                                delaySearchTimer = null;
                            }
                            
                            if (this.loadDelay){
								var self = this;
                                delaySearchTimer = win.setTimeout(function(){ self.delayLoad(val); }, this.loadDelay);
                            } else {
                                this.loadData(val);
                            }
                            
                        }
                    } else {
                        this.clear && this.clear.cssDisplay(0);
                        this.display(0);
                    }
                    
                    //objSearch.onchange && objSearch.onchange.call(objSearch, val);
                },
                
                delayLoad : function(val){
                    if (this.val === val) {
                        this.loadData(val);
                    }
                },
                
                loadData : function(key){
                    this.loadXhr && this.loadXhr.abort();
                    
                    //var params = $.makeArray(arguments);
                    //params = params.concat(Util.getBind(this, 'loadComplete'), objSearch.extendParams && objSearch.extendParams.wb);

                    //this.loadXhr = (objSearch.sUrl||this.sUrl).apply(this, params);
                    this.loadXhr = this.sUrl(key, Util.getBind(this, 'loadComplete'), objSearch.extendParams && objSearch.extendParams.wb);
                },
                
                loadComplete : objSearch.loadComplete || function(e){
                    if (e.isOk()) {
                        var reqData = e.reqCfg.data,
                            kw = reqData.k,
                            data = e.getData();
						if( data.total_number == 0 ) {  //返回数据为空
							$(this.getView()).html('<li class="no-data">呃，没有记录哦</li>');
							this.display(1);
						    return false; 
						}    
                        this.cache[kw] = data;
                        
                        if (this.val === kw) {
                            //if (objSearch.parseData) data = objSearch.parseData(data);
                            this.showResult(data)
                        }
                    }
                    
                    this.loadXhr = NULL;
                }, 

               
                showResult : objSearch.showResult || function(data) {
                    var $view = $(this.getView()), spots = data.spots,state, limit = this.outLimit, num = 1;
					if (data.total_number != '0') {
                        var htmls = [], url;
                        $.each(spots, function(i, r){
							name = r.name;
							if(r.type == 2) {
								url = Req.mkUrl('spots', 'citySpots', {pid: r.province_id, id: r.id,cid:r.city_id ,'_r':NULL});
							} else{
								url = Req.mkUrl('spots', 'detail', {name: name, id: r.id, '_r':NULL});
							}
                            htmls.push('<li><a href="'+url+'" rel="'+r.id+'">' + '<span>' + r.province_name + '</span>' + name + '</a></li>');
							num ++;
							if(limit && num>limit) return false; 														
                        });
                        $view.html(htmls.join(''));
                        
                        this.selectNext();
                        state = objSearch.affixfun(data);
                    } else {
                        $view.html('<li class="no-data">呃，没有记录哦</li>');
                    }
                    this.clear && this.clear.cssDisplay(1);
                    //!state && this.display(1);
					this.display(1);
                },
				
				display : function(b){
					mod.AutoComplete.prototype.display.call(this,b);
					
					if(Util.ie6){
						var $view = $(this.getView());
						this.jqIframe = this.getIframe();
						if(b){
							$view.after(this.jqIframe);
							this.jqIframe.css({
								top:$view.css('top'),
								left:$view.css('left'),
								width:$view.width(),
								height:$view.height(),
								zoom:1
							});
						} else {
							this.jqIframe.remove();
						}
					}
					
				},
				
				getIframe : function(){
					if(!this.jqIframe){
						this.jqIframe = $('<iframe class="shade-iframe" frameborder="0"></iframe>');
						this.jqIframe.css({
							position: 'absolute'
						});
					} 
					return this.jqIframe;
				},
                
                onViewReady : function(){
                    mod.AutoComplete.prototype.onViewReady.call(this);
					
                   var self = this;
                    if (objSearch.catchClick) {
                        this.jq().click(function(e){
							e.preventDefault(1);
                            self.onEnter(e);
                        })
                    }
					if(objSearch.catchEnter){
						this.inputor.keydown(function(e){
							if(e.keyCode == 13){
								self.onEnter(e);
								e.preventDefault(1);
								this.blur();
							}
						});
					}					
                }
            }
        });
        
        search.getView();
        
        if (this.clear) {
            search.clear = this.jq(this.clear).click(function(e){
                search.reset();
                search.inputor.focus();
                e.preventDefault();
            });
            
        }
    }
}

}))

//景点中的微博元素
mod.spotItem = X.reg('SpotItem', Util.create(Base, {
    //图片数
    //imgNum : 0,
    
    //imgs : [],
    
    //加载完成回调（主要是图片，如果没图片的立即回调)
    onload : null,
    
    //检测图片
    initUI : function() {
        var $view = $(this.html);
        
        var $imgs = $view.find('#pvImg>img');
        
        if ($imgs.length){
            var self = this;
            
            $imgs.bind({
                load : function(){
                    self.onload && self.onload(0, $view);
                },
                error : function() {
                    self.onload && self.onload(1, $view);
                }
            })
        } else {
            this.onload && this.onload(1);
        }
        
        this.view = $view[0];
        
        delete this.html;
    }
})); 


//游记的微博卡片
mod.spotItem = X.reg('youjiItem', Util.create(Base, {

    //加载完成回调（主要是图片，如果没图片的立即回调)
    onload : null,
    
    //检测图片
    initUI : function() {
        var $view = $(this.html);
        
        var $imgs = $view.find('p.pic img');
        
        if ($imgs.length){
            var self = this;
            
            $imgs.bind({
                load : function(){
                    self.onload && self.onload(0, $view);
                },
                error : function() {
                    self.onload && self.onload(1, $view);
                }
            })
        } else {
            this.onload && this.onload(1, $view);
        }
        
        this.view = $view[0];
        
        delete this.html;
    }
})); 

X.reg('ImageShow', function(){

    var inst = X.use('Box', {
        view : 'ImageView',
        
        autoRender : TRUE,
		
		hasCmt : TRUE,
		
		operationStatus : 'operationStatusSpots',
        
        hidden : FALSE,
        
        mask : TRUE,
        
        closeable: TRUE,
        
        appendTo : 'body',
		
		index : 0,
		
		actionMgr:true,
		
		onactiontrig:function(e){
			switch(e.get('e')){
				case 'prev' :
					if(this.index == 0){
						//	this.jq('#aPrev').attr('class','arrow-prev arrow-prev-disable'); return;
						this.index = this.WbList.length;
					}
					this.load(this.WbList[this.index-1]);
					break;
				case 'next' :
					if(this.index == this.WbList.length-1){
						//this.jq('#aNext').attr('class','arrow-next arrow-next-disable'); return;
						this.index = -1;
					}
					this.load(this.WbList[this.index+1]);
					break;
				case 'right':
					this.flag = !this.flag;
					this.jq('#ctn img').imgRotate('right');
					var img = this.jq('#ctn').children()[0];
					if(this.flag){
						this.picLoaded(this._height,this._width,img);
					} else {
						this.picLoaded(this._width,this._height,img);
					}
					
					break;
				case 'left':
					this.flag = !this.flag;
					this.jq('#ctn img').imgRotate('left');
					var img = this.jq('#ctn').children()[0];
					if(this.flag){
						this.picLoaded(this._height,this._width,img);
					} else {
						this.picLoaded(this._width,this._height,img);
					}
					break;
				case 'cm' : 
					this.cmtBox.jqInputor.focus();
					break;
				default:
					e.stopPropagation(false);
					
			}
		},
		
		close : function(){
			this.cmtBox.jqInputor.blur();
			return ui.Base.prototype.close.apply(this,arguments);
		},	
		
		onViewReady:function(){
			var self = this,
				wbList = getCfg('wbList');
			this.WbList=[];
			for(var key in wbList){
				if(+wbList[key].has_img){
					wbList[key].ext = $.parseJSON(wbList[key].ext);
					self.WbList.push(wbList[key]); 
				}
			}
			var cmtCon = this.jq('#cmtBox');
			cmtCon.find('a.ico-face').cssDisplay(0);
			this.cmtBox  = X.use('CmtBox', {
					view : this.jq('#cmtBox')[0],
					wbId : this.wbId,
					emoIndex : 20009,
					showEmotion : false,
					commentUrl : Req.comment,
					replyUrl : Req.reply,
					cmtError : function(e){
						self.jq('#errorTips').cssDisplay(1).text(e.getMsg());
					},
					pCt  : this
				});
				
			X.on('Cmt.afterSend',Util.getBind(this,'afterSend') );
			
			this.cmtBox.getView();
			this.jq('#ctn').css({overflow:'hidden'});
			
			this.jq('#sync').change(function(){
				if(this.checked){
					$(this).addClass('checked');
				} else {
					$(this).removeClass('checked');
				}
			});
			
			this.cmtBox.jqInputor.focusText('随便说几句……','focus-s2',this.cmtBox.jq('.normal-s2'),3);
			this.cmtBox.checkText = function(){
				var v = mod.CmtBox.prototype.checkText.call(this,arguments);
				if(v == '随便说几句……') return false;
				else return v;
			};
		},
		afterSend : function(e){
			this.jq('#errorTips').cssDisplay(0);
			if(e.isOk){
				var $src = this.jq('#cCount').parent()
					,offset = $src.offset()
					,$em = $src.find('em');
					
				var img = $('<img src="/img/comt.png"/>').appendTo('body');
				img.css({
					position: 'absolute',
					width : 14,
					top : offset.top,
					left : offset.left,
					height : 14,
					'z-index':100000
				});
				img.animate({
					top :  offset.top - 14,
					left: offset.left - 4,
					width : 25,
					height:25,
					opacity: 0.4
				},500,function(){
					img.remove();
					$src.removeClass('ico-comment').addClass('ico-commented');
					if ($em.length) {
						$em.text(parseInt($em.text())+1);
					}
				});
				this.cmtBox.jqInputor.val('随便说几句……');
			}else{
				this.jq('#errorTips').text(e.getMsg());
				//MB.alert('',e.getMsg());
			}
		},
        
        //展示图片
        load : function(wb) {
            this.index = $.inArray(wb,this.WbList);

			//this.jq('#aPrev').attr('class',this.index == 0 ? 'arrow-prev arrow-prev-disable' :'arrow-prev');
			//this.jq('#aNext').attr('class',(this.index == this.WbList.length-1 ? 'arrow-next arrow-next-disable' :'arrow-next'));
			
			this.fixedOffset();
			$(this.mask).css('opacity',0.9);
			
			this.jq('#xweibo_loading').cssDisplay(1);
			
            var img = new Image(),
                self = this;
            
            img.onload = function(){
                self.picLoaded(this.height,this.width,this,'load');
            };
			
			if(typeof wb.ext == 'string'){
				wb.ext = eval('('+wb.ext+')');
			}
			
            img.src = wb.ext.pic.big || wb.ext.pic.small;
			
			this.jq('.ico-src').attr('href',img.src);
			this.jq('#cCount').html(wb.comments);
			this.jq('#fCount').html(wb.likes);	
			this.jq('#fCount').parent()
				.attr({
					'class':wb.liked?'ico-liked':'ico-like',
					'rel':'e:like,s:'+ wb.spots_id +',w:'+ wb.id+',un:1'
					})
				.data('xwb_rel',null);
			this.cmtBox.wbId = wb.id;
			this.cmtBox.jqInputor.val('随便说几句……');
        },
        
		fixedOffset:function(){
			if( !Util.ie6 ){
				var ui = this.jq('.win-enlarge');
				ui.css({marginTop:-ui.height()/2,marginLeft:-ui.width()/2});
			}
		},
		
        picLoaded : function(img_h,img_w,img,type) {
            var $win = $(win),
                win_h = parseFloat($win.height()),
                win_w = parseFloat($win.width()),
                
                toHeight = img_h,
                toWidth = img_w,
				mt = 0,
                self = this,
				
                $jq = this.jq();
				
            $jq.find('#ctn').stop();
			var toHeight = img_h + 100 > win_h ? win_h - 100 : img_h;
			if(toHeight/img_h * img_w > 660){
				toHeight = 660 / img_w * img_h;
				mt = - (toHeight+100)/2;
				$jq.find('#ctn').css('paddingTop',30);
			} else {
				$jq.find('#ctn').css('paddingTop',30);
				if(getCfg('uid')){
					toHeight = toHeight + 150 >= win_h ? toHeight - 75 : toHeight;
					mt = - (toHeight+150)/2 + 20;
				} else {
					toHeight = toHeight + 150 > win_h ? toHeight - 50 : toHeight;
					mt = - (toHeight+150)/2 + 40;
				}
			}

			this.jq('#xweibo_loading').cssDisplay(0);
			type == 'load' && $jq.find('#ctn').empty().append(img);
			
			if(type == 'load'){
				this._height = toHeight;
				this._width = toHeight/img_h * img_w;
				this.flag = true;
			}
			
			var ver =  parseInt($.browser.version);
			if( $.browser.msie && (document.documentMode || ver) < 9){
				if(!this.flag)
					$(img).attr({width:toHeight,height:null});
				else 
					$(img).attr({width:null,height:toHeight});
			} else {
				$(img).height(toHeight).width(toHeight/img_h * img_w);
			}
			
			this.jq('.win-enlarge').css({marginTop:mt});
			$jq.find('#ctn').animate({height:toHeight});

        },
		
		setOffset : function(){
			var btop = $(document).scrollTop(), 
			$win = $(win),
            win_h = parseFloat($win.height()),
			win_w = parseFloat($win.width()),
			jq = this.jq();
			var wintop = jq.find('div.win-pop'), wtop = wintop.offset().top, wleft = wintop.offset().left, ltop = btop+wtop;
			jq.css({'position':'absolute','z-index':wintop.css('z-index')+1}).offset({top:btop+win_h/2,left:win_w/2});
		},
		
		beforeShow : function(){
			ui.Box.prototype.beforeShow.call(this);
			$(this.mask).css('z-index',20008);
		}
    })
    
    X.reg('ImageShow', inst, TRUE);
    
    return inst;
});

//评论发布框
X.reg('CommentBox', function(cfg){
    var parent = ui.Box.prototype;
    
    var inst = X.use('Box', $.extend({
        contentHtml : 'sendBox',
        appendTo : 'body',
        mask : TRUE,
        cs : 'win-comment win-fixed',
        closeable : TRUE,
        topic : '我来评论',
        btnText : '评论',
        
        //关联的微博ID
        wid : NULL,
        
        //触发的元素
        src : NULL,
        
        sync : NULL,
        input : NULL,
        appendHtml : '<p><label><input type="checkbox" id="sync">同时发布到我的微博</label></p>',
        
        //字符限制
        textLimit : 140,
        
        actionMgr : TRUE,
        
        _inputKeyupHandler : NULL,
        
        onactiontrig : function(e){
            switch (e.data.e) {
            case 'sd':
                !this.lock() && this.checkText() && this.send();
                break;
            }
        },
        
        onViewReady : function() {
            this.input = this.jq('textarea');
            this.sync = this.jq('#sync');
            this.jqErrTip = this.jq('#errTip');
            
            this._inputKeyupHandler = Util.getBind(this, 'onInputKeyup');
            
            parent.onViewReady.call(this);
        },
        
        beforeShow : function() {
            this.input.keyup(this._inputKeyupHandler);
            parent.beforeShow.call(this);
        },
        
        afterShow : function(){
            this.input.focus();
            parent.afterShow.call(this);
        },
        
        afterHide : function() {
            this.input.unbind('keyup', this._inputKeyupHandler);
            parent.afterHide.call(this);
        },
        
        onInputKeyup : function(e) {
            if (!this.lock() && this.checkText()){
                if(e.ctrlKey && ( e.which == 13||e.which == 10 )) {
                    this.send();
                }
            }
        },
        
        send : function() {
            this.lock(1);
            this.comment( 
              this.wid, 
              this.input.val(), 
              this.sync.attr('checked')?1:0, 
              1,
              Util.getBind(this, 'onSendLoad'),
              { data:$.extend({_route:X.getModule()},this._data) }
             )
        },
		comment : function(){
			if(this._data.hasOwnProperty('wid')){
				Req.youjiComment.apply(Req,arguments);
			} else {
				Req.comment.apply(Req,arguments);
			}
		},
        
        onSendLoad : function(e) {
            if (e.isOk()){
                this.display(0);
				
				//更新缓存数据
				var wbList = getCfg('wbList'),count;
				wbList && wbList[this.wid] && (count = wbList[this.wid].comments = + wbList[this.wid].comments  + 1);
               
			   var src = this.src;
                if (src) {
					var $src = $(src)
						,offset = $src.offset()
						,$em = $src.find('em');
						
					count  = count == undefined ?  parseInt($em.text())+1 :count;
					var img = $('<img src="/img/comt.png"/>').appendTo('body');
					img.css({
						position: 'absolute',
						width : 14,
						top : offset.top,
						left : offset.left,
						height : 14
					});
					img.animate({
						top :  offset.top - 14,
						left: offset.left - 4,
						width : 25,
						height:25,
						opacity: 0.4
					},500,function(){
						img.remove();
						$src.removeClass('ico-comment').addClass('ico-commented');
						if ($em.length) {
							$em.text(count);
						}
					});
                }
                
                this.reset();
            } else {
                this.jqErrTip.text(e.getMsg()).cssDisplay(1);
                this.input.focus();
            }
            this.lock(0);
        },
        
        //检查内容（字数是否超过）
        checkText : function(){
            var input = this.input;
            
            var v = input.val(),
                $errTip = this.jqErrTip;
                
            //输入为空
            if (!v || !$.trim(v)) {
                $errTip.text('请输入内容').cssDisplay(1);
                input.focus();
                return FALSE;
            }

            $errTip.cssDisplay(0);
            
            var left = Util.calWbText(v);
            
            if (left < 0) {
                input.val(Util.byteCut(v, this.textLimit*2));
            }
            
            return TRUE;
        },
        
        setParams : function(pm) {
            var val;
            for (var i in pm) {
                val = pm[i];
                
                switch (i) {
                case 'wid':
                    this.wid = val;
                    break;
                
                case 'text':
                    this.input.text(val);
                    break;
                    
                case 'src':
                    this.src = val;
                    break;
				case 'data':
					this._data = val;
					break;
                }
            }
			
            if(this._data.hasOwnProperty('wid')){
				if(this._data['wid']){
					this.sync.parent().cssDisplay(1);
				} else {
					this.sync.parent().cssDisplay(0);
				}
			}
            return this;
        },
        
        reset : function() {
            this.input.val('');
            this.src = NULL;
            //this.sync.attr('checked', false);
        }
        
    }, cfg));
    
    X.reg('CommentBox', inst, TRUE);
    return inst;
});



/**
 * @class Xwb.mod.myMsg
 * 发短消息弹出框
 * @extends Xwb.ui.Box
 * @singleton
 */
X.reg('myMsg', function(){

	var inst = X.use('Box', function(proto){

	return {
		contentHtml:'Msg',
		appendTo:doc.body,
		cs:'win-form win-form-s1 win-fixed',
		actionMgr : true,
		title: getText('发短消息'),
		//autoCenter : true,
		closeable:true,
		mask:true,
		onViewReady : function( v ){
			var self = this;
			this.jqExtra('word', 'warn', 'sender', 'content', 'warnPos', 'uid', 'nullWord');
			this.jqContent.keyup(Util.bind(this.checkText, this));
			this.jqSender.blur(function(){
				var v = $.trim(this.value);
				self.checkFans(v,1,null,true);
			});
			this.selectionHolder = X.use('SelectionHolder', {elem:this.jqContent[0]});
	/*         this.atWho = X.use('atWho',{
				appendTo : doc.body,
				Inputor : this.jqSender,
				autoRender : true,
				format : function(data) {
					return data.nickname
				},
				afterChoose : function() {
					self.jqContent.focus();
				},
				noAt:true
			});  */
		},
		
		checkText : function(){
			this.jqNullWord.cssDisplay(0);
			var v = $.trim(this.jqContent.val()),
				left = Util.calWbText(v, 140);
			if(left >=0){
				this.jqWord.html(left).removeClass('tips-on').cssDisplay(1);;
			}else{
				this.jqWord.html(left).addClass('tips-on').cssDisplay(1);;
			}
			return left>=0 && v;
		},
		
		afterShow : function(){
			proto.afterShow.call(this);
			if( this.jqSender.val() === '' )
				this.jqSender.focus();
			else this.jqContent.focus();
		},
		
		onactiontrig : function( e ){
			switch(e.data.e){
				// 点击发送
				case 'sd' :
					this.send();
				break;
				case 'ic':
					 X.use('emotion')
					  .setSelectionHolder( this.selectionHolder , this.checkText, this)
					  .showAt(e.src);
				break;
				case 'c' : 
					this.display(0);
				break;
			}
		},
		
		send : function(){
			if(!this.sending){
				var d = this.validate(), 
					fn = Util.getBind(this, 'onSendLoad'),
					sndBtn = this.jqSendBtn;
				if(d){
					this.checkFans( d.u, d.t, function(){
						Util.disable( sndBtn, true);
						//Req.msg(encodeURIComponent(d.u), d.t, d.c, fn);
						Req.msg(d.u, d.t, d.c, fn);
					});
				}
			}
		},
		
		onSendLoad : function( e ){
			if(e.isOk()){
				this.display(false);
				MB.success('','发送成功！')
				//location.reload();
			}else {
				var msg, self = this;
				switch(e.getCode()){
					case 20014:
						MB.alert('', e.getMsg());
						break;
					case 1010005:
						MB.alert('',getText('内容长度不能超过140个字。'),function(){
							self.jqContent.focus();
						});
						break;
					case 2442202:						
						MB.alert('',e.getMsg(),function(){
							self.jqContent.focus();
						});
						
						break;
					default : msg = e.getMsg('', '短消息' );
				}
				if(msg && this.display()){
					this.jqWarnPos.cssDisplay(true).text(msg);             
				}
			}
			this.sending = false;
			Util.disable( this.jqSendBtn, false);
		},
		
		checkFans : function(user, type, onsuccess, disableFocus){
			 var self = this; 

			if (!user)
			{
				self.jqWarnPos.cssDisplay(true)
					.text( getText('请输入要发送的用户昵称') );
				return;
			}
			self.jqWarnPos.cssDisplay(false);

			onsuccess && onsuccess();
			  // 对方是否为我的粉丝
		},
		
		/***/
		reset : function(){
			this.jqSender.attr('disabled', false).val('');
			this.jqContent.val('');
			this.jqUid.val('');
			this.jqWarnPos.cssDisplay(false);
			this.checkText();
			return this;
		},
		
		validate : function(){
			var name    = $.trim(this.jqSender.val()),
				content = this.checkText(),
				uid     = this.jqUid.val();
			
			if(!name){
				this.jqSender.focus();
				return;
			}
			
			if(!content){
			
				if(!$.trim(this.jqContent.val()).length){
					this.jqWord.cssDisplay(0);
					this.jqNullWord.cssDisplay(1);
				}
				//else MB.tipWarn( getText('内容长度不能超过140个字。') );
				this.jqContent.focus();
				return;
			}
			
			if(uid)
				return {u:uid, c:content};
			return {u:name, c:content,t:1};
		},
		
		reply : function(uid, name){
			this.getView();
			this.reset();
			this.display(true);
			this.jqSender.val(name).attr('disabled', true);
			this.jqUid.val(uid);
			this.jqContent.focus();
			this.checkText();
		}
	};

	});



	X.reg('myMsg', inst, true);

	return inst;

});


/**
 * 选择我擅长的问题
 */
X.reg('expExpert', function(data){
	var inst = X.use('Box', function(){
	return {
		contentHtml:'expExpert',
		appendTo:doc.body,
		cs:'win-pop win-form win-form-s1 win-fixed',
		actionMgr : true,
		title: getText('选择'),
		closeable:true,
		mask:true,
		autoRender : true,
		hidden : false,
		onViewReady : function( v ){
			var type = data.type, spots = data.spots, txtType = [], txtSpots = [];
			for(var i in type){
				txtType.push('<label><input type="radio" name="spotType" value="' + i + '">' + type[i] + '</label>');
			}
			for(var i in spots){
				txtSpots.push('<option value="' + spots[i].id + '">' + spots[i].name + '</option>');
			}
			this.jq('.options').append($(txtType.join(''))).find('input').first().attr('checked', 'checked');
			this.jq('select').append($(txtSpots.join('')));
		},
		afterShow : function(){
		
		},
		getType : function(){
			var id = this.jq('input:checked').val(), val = this.jq('input:checked').parent()[0].childNodes[1].data;
			return {id:id, val:val};
		},
		getId : function(){
			var id = this.jq('select').val(), val = this.jq('select option[value='+ id +']').html();
			return {id:id, val:val};

		},
		onactiontrig : function( e ){
			switch(e.data.e){
				case 'ok' :
					data.callback();
				break;
				case 'cc':
					this.display(0)
				break;
			}
		},		
		
		ok : function(){
			
		}
	};

	});



	X.reg('myMsg', inst, true);

	return inst;

});


//想去、去过的状态设置框
mod.stateBox = X.reg('StateBox', function(cfg){
    
    cfg = cfg || {};
    
    $.extend(cfg, {
        mask: TRUE,
        
        closeable : TRUE,
        
        appendTo : 'body',
        
        cs : 'win-modify win-fixed',
        
        contentHtml : 'StateContent',
        
        actionMgr : TRUE,
        
        okHandler : $.noop,
        
        onactiontrig : function(e){
            switch (e.data.e){
            case 'cls': //取消
                this.close();
                break;
                
            case 'ok': //确定
                if (this.okHandler(this.jq('input:checked').val()) !== false) {
                    this.close();
                }
                break;
            }
        },
        
        setOkHandler : function(fn){
            this.okHandler = fn;
            
            return this;
        },
        
        setRadio : function(stat) {
            var $radio = this.jq('input');
            
            $radio.each(function(i, ele){
                var $ele = $(ele);
                $ele.attr('checked', $ele.val() == stat);
            });
            
            return this;
        },
        
        onViewReady : function(){
            
        }
    });
    
    var inst = X.use('Box', cfg)
    
    X.reg('StateBox', inst, TRUE);
    
    return inst;
});


//我的景点浮层
X.reg('MySpot', function(cfg){

    var inst = X.use('Box', $.extend({
       contentHtml : 'mySpot',
       boxOutterHtml : 'ArrowBoxBottom',
       wantToSpots : 'Loading',
       visitedSpots : 'Loading',
       
       cs : 'win-attraction',
       
       contextable : TRUE,
       
       autoRender : TRUE,
       
       refresh: FALSE,
       
       onViewReady : function(){
           ui.Layer.prototype.onViewReady.call(this);
           
           this.getSpot();
           
           var self = this;
           
           X.on('api.setStateSpots', function(){
               self.refresh = TRUE;
           });
       },
       
       afterShow : function() {
           if (this.refresh) {
               this.getSpot();
               this.refresh = FALSE;
           }
           
           ui.Box.prototype.afterShow.call(this);
       },
       
       getSpot : function() {
           Req.mySpots(Util.getBind(this, 'onLoad'));
       },
       
       createList : function(data) {
           var htmls = [], params, action, spot_name;
           $.each(data, function(i, r) {
              spot_name = r.name;
              params = {name: spot_name, id: r.spots_id};
              
              if (r.type == 2) {
                  action = 'citySpots';
                  params = $.extend(params, {pid: r.pid, cid: r.cid});
              } else {
                  r.type = 2;
              }
              
              htmls.push('<a href="'+Req.mkUrl('spots', action, params)+'">' + spot_name + '</a>') ;
           });
           
           return htmls.join('');
       },
       
       onLoad : function(e) {
           var $wantTo = this.jq('#w_list'),
                $visited = this.jq('#v_list');
                
           if (e.isOk()) {
               var data = e.getData(),
                    wantToList = data[1],
                    visitedList = data[2];
                    
               if (wantToList && wantToList.length) {
                   $wantTo.html(this.createList(wantToList));
               } else {
                   $wantTo.html('你还没有想去的地方~');
               }
               
               if (visitedList && visitedList.length) {
                   $visited.html(this.createList(visitedList));
               } else {
                   $visited.html('你还没去过任何地方~');
               }
               
           } else {
               $wantTo.html('查询失败');
               $visited.html('查询失败');
           }
       }
   }, cfg));
   
   X.reg('MySpot', inst, TRUE);
   
   return inst;
});


//图片评论浮层
X.reg('youjiImg',function(cfg){
	
	    var inst = X.use('Box', {
        view : 'ImageView',
        
        autoRender : TRUE,
        
        hidden : FALSE,
        
        mask : TRUE,
		
		hasCmt : cfg.hasCmt,
		
		operationStatus : 'operationStatusYouji',
        
        closeable: TRUE,
        
        appendTo : 'body',
		
		index : 0,		
		
		actionMgr:true,
		
		paramData :{data:{}},
		
		onactiontrig:function(e){
			switch(e.get('e')){
				case 'prev' :
					if(this.index == 0){
						this.index = this.srcList.length;
					}
					var nowIndex = this.index-1, obj = this.srcList[nowIndex], src = obj;
					if(typeof obj == 'object'){
						this.pid = obj.pid;
						this.yid = obj.yid;
						src = obj.url;
					}
					this.reply(src);
					break;
				case 'next' :
					if(this.index == this.srcList.length-1){
						this.index = -1;
					}
					var nowIndex = this.index+1, obj = this.srcList[nowIndex], src = obj;
					if(typeof obj == 'object'){
						this.pid = obj.pid;
						this.yid = obj.yid;
						src = obj.url;
					}
					this.reply(src);
					break;
				case 'right':
					this.flag = !this.flag;
					this.jq('#ctn img').imgRotate('right');
					var img = this.jq('#ctn').children()[0];
					if(this.flag){
						this.picLoaded(this._height,this._width,img);
					} else {
						this.picLoaded(this._width,this._height,img);
					}
					
					break;
				case 'left':
					this.flag = !this.flag;
					this.jq('#ctn img').imgRotate('left');
					var img = this.jq('#ctn').children()[0];
					if(this.flag){
						this.picLoaded(this._height,this._width,img);
					} else {
						this.picLoaded(this._width,this._height,img);
					}
					break;
				default:
					e.stopPropagation(false);
					
			}
		},
		close : function(){
			if(this.hasCmt) this.cmtBox.jqInputor.blur();
			return ui.Base.prototype.close.apply(this,arguments);
		},
		
		youjiComment : function(id, text, forward, hpt, fn, cfg){	
			Req.act('commentsApi', 'comment', {
				id:id || this.yid,
				text:text,
				forward : forward,
				pid : this.pid || '',
				//ext : ext,
				type:hpt
			   }, fn, cfg
			);
		},
		
		getPicInfoByPid : function(pid){
			var pics = X.getCfg('youji').img_data;
			for(var i=0,j=pics.length;i<j;i++){
				if(pics[i].id == pid){					
					return pics[i];
				}				
			};
			return '';
		},
		
		onViewReady:function(){
			var self = this;
			
				this.cmtBox  = X.use('CmtBox', {
						view : this.jq('#cmtBox')[0],
						emoIndex : 20009,
						wbId : getCfg('youji') && getCfg('youji').id,
						commentUrl : Util.bind(this.youjiComment, this),
						localComments:true,
						pCt  : this
					});
					
				X.on('Cmt.afterSend',Util.getBind(this,'afterSend') );
				
				this.cmtBox.getView();
				
				this.jq('#sync').change(function(){
					if(this.checked){
						$(this).addClass('checked');
					} else {
						$(this).removeClass('checked');
					}
				});
			
				if(!getCfg('wbList'))	this.jq('#sync').parent().cssDisplay(0);
				
				this.cmtBox.jqInputor.focusText('随便说几句……','focus-s2',this.cmtBox.jq('.normal-s2'),3);
				this.cmtBox.checkText = function(){
					var v = mod.CmtBox.prototype.checkText.call(this,arguments);
					if(v == '随便说几句……') return false;
					else return v;
				};
			
			if(!this.hasCmt){
				this.jq('#cmtBox').cssDisplay(0);
			}
			this.jq('#ctn').css({overflow:'hidden', height: 100});
				
			this.jq('#Showcomments').click(function(){
				if(self.yid){
					window.location.href = Req.mkUrl('youji','',{id:self.yid});
					return;
				}
				
			    var scrollto = 400000,
				    $cmtElm1 = $('div.tour-comment'),
					$cmtElm2 = $('div.add-comment');
				if( $cmtElm1[0] ){
					scrollto = $cmtElm1.offset().top;
				}else if( $cmtElm2[0] ){
					scrollto = $cmtElm2.offset().top - 20;
				}
				$('html,body').animate({'scrollTop': scrollto},300);
				self.close();
				self.jq('.opera-status').cssDisplay(0);
				return false;
			});
			
			
			this.fixedOffset();
			
			this.oriSrcList=[];
			this.srcList = [];
			this.thList=[];
			if(this.hasCmt){
				var imgData = getCfg('youji').img_data;
				if(imgData){
					if(typeof imgData == 'string') imgData = $.parseJSON(getCfg('youji').img_data)
					$(imgData).each(function(){
						self.oriSrcList.push(this.original_pic.url);
						self.srcList.push(this.web_pic.url);
						self.thList.push(this.thumbnail_pic.url);
					}); 
				}
			}else{
				this.srcList = cfg.srcList;
			}
			if(__debug) console.log(self.srcList);
		},
		afterSend : function(e){
			if(e.isOk()){
				this.jq('.opera-status').cssDisplay(1);
				this.cmtBox.jqInputor.val('随便说几句……');
			}
			this.cmtBox._param =  $.extend(true,{},this.paramData);
		},
        
		
		srcListIsString : cfg.srcListIsString === false ? false : true ,  //数组相片对象内为字符串
		
        //展示图片
        reply : function(src,wid) {
			this.display(1);
            this.index = this.srcListIsString ? $.inArray(src,this.srcList) : this.getIndex(src);

			$(this.mask).css('opacity',0.9);
			
			this.jq('#xweibo_loading').cssDisplay(1);
			this.jq('.opera-status').cssDisplay(0);
			//if(this.hasCmt)
				this.cmtBox.jqInputor.val('随便说几句……');

			this.paramData.data.imgUrl = this.thList[this.index];   //缩略图
			
			var type = this.srcList[this.index].type;

			if(type){
				if(type == 3){
					this.jq('#cmtBox').cssDisplay(0);
				}else{
					this.jq('#cmtBox').cssDisplay(1);
				}
			}
			
			wid && (this.paramData.data.wid = wid);
			
			//if(this.hasCmt) 
				this.cmtBox._param = $.extend(true,{},this.paramData);
			
            var img = new Image(),
                self = this;

            img.onload = function(){
                self.picLoaded(this.height,this.width,img,'load');
            };
            
            img.src = this.oriSrcList[this.index] || src;  // 改为优先显示原图
			
			this.jq('.ico-src').attr('href', img.src);
			
			var youji = Xwb.cfg.youji; 
			if(youji){
				youji.like_count = youji.like_count ? +youji.like_count : 0; 
				this.jq('#fCount').html(youji.like_count);	
				this.jq('#fCount').parent().attr({
						'class':youji.whether_liked?'ico-liked':'ico-like',
						'rel':'e:like,s:'+ youji.spots_id +',y:'+ youji.id+',un:1,t:1'
				});
			}
        },
		
		getIndex : function(src){
			this.srcList = getCfg('srcList');
			for(var i=0, len = this.srcList.length;i<len;i++){
				if(src == this.srcList[i].url) return i;
			}
		},
        
		fixedOffset:function(){
			if(!Util.ie6) {
				var ui = this.jq('.win-enlarge');
				ui.css({marginTop:-ui.height()/2,marginLeft:-ui.width()/2});
			}
		},
		
       picLoaded : function(img_h,img_w,img,type) {
            var $win = $(win),
                win_h = parseFloat($win.height()),
                
                toHeight = img_h,
                toWidth = img_w,
				mt = 0,
                self = this,
				
                $jq = this.jq();
			
            $jq.find('#ctn').stop();

			var toHeight = img_h + 100 > win_h ? win_h - 100 : img_h;
			if(toHeight/img_h * img_w > 660){
				toHeight = 660 / img_w * img_h;
				mt = - (toHeight+100)/2;
				$jq.find('#ctn').css('paddingTop',30);
			} else {
				$jq.find('#ctn').css('paddingTop',30);
				if(getCfg('uid')){
					toHeight = toHeight + 150 >= win_h ? toHeight - 75 : toHeight;
					mt = - (toHeight+150)/2 + 20;
				} else {
					toHeight = toHeight + 150 > win_h ? toHeight - 50 : toHeight;
					mt = - (toHeight+150)/2 + 40;
				}
			}
			
			this.jq('#xweibo_loading').cssDisplay(0);
			type == 'load' && $jq.find('#ctn').empty().append(img);

			if(type == 'load'){
				this._height = toHeight;
				this._width = toHeight/img_h * img_w;
				this.flag = true;
			}
				
			var ver =  parseInt($.browser.version);
			if( $.browser.msie && (document.documentMode || ver) < 9){
				if(!this.flag)
					$(img).attr({width:toHeight,height:null});
				else 
					$(img).attr({width:null,height:toHeight});
			} else {
				$(img).height(toHeight).width(toHeight/img_h * img_w);
			}
						
			this.jq('.win-enlarge').css({marginTop:mt});
			$jq.find('#ctn').animate({height:toHeight});
        },
		
		setOffset : function(){
			var btop = $(document).scrollTop(), 
			$win = $(win),
            win_h = parseFloat($win.height()),
			win_w = parseFloat($win.width()),
			jq = this.jq();
			var wintop = jq.find('div.win-pop'), wtop = wintop.offset().top, wleft = wintop.offset().left, ltop = btop+wtop;
			jq.css({'position':'absolute','z-index':wintop.css('z-index')+10}).offset({top:btop+win_h/2,left:win_w/2});
		},
		
		beforeShow : function(){
			ui.Box.prototype.beforeShow.call(this);
			$(this.mask).css('z-index',20008);
		}
		
		
    });
	X.reg('youjiImg',inst,true);
	return inst;
});



function YJ_Image(b, wrap){
    var $w = this.$w = $(wrap);
    
    var $box = this.$b = $(b).find('div.img-box');
    
    var cls = $w.attr('class');
    
    this.mode = $.trim(cls).replace(/-/g, '_');
    
    //console.log(this.mode);
    
    this.src = $box.attr('p');
    
    //width 
    this.w = $box.attr('dw');
    
    //height
    this.h = $box.attr('dh');
    
    //hasText
    this.hasText = $box.attr('rev');
}
YJ_Image.prototype = {
    //加载图片
    load : function(){
        var img = new Image();
        var onloaded = Util.getBind(this, 'onloaded');
        img.onload = function(){
            onloaded(this);
            
            //释放
            img = onloaded = null;
        }
        img.src = this.src;
    },
    
    //图片加载完成
    onloaded : function(img){
        var $b = this.$b;
        
        $b
        .empty()
        .append(img);
        
        this.fixImg($b, img);
        
        this.afterLoaded && this.afterLoaded();
    },
    
    fixImg : function($p, img){
        var iw = img.width,
            ih = img.height;

        /*
        if (!img.height || !img.width) {
            console.log(img);
            setTimeout(Util.getBind(this, 'fixImg'), 10, $p, img);
            return;
        }
        */

        var
            //parent width
            pw = $p.width(),
            
            minHeight = parseInt($p.css('min-height') || 0),
            
            //parent height
            ph = $p.height(),
            
            //target width
            tw,
            
            //target height,
            th;

        if ( ph < minHeight ) {
            ph = minHeight;
        }
            
        var
            //横向比例 容器宽：图片宽
            xscale = pw/parseFloat(iw),
            //窗口高：图片高
            yscale = ph/parseFloat(ih),
            //容器高：容器宽
            //pscale = pw/parseFloat(ph),
            //图片宽：图片高
            iscale = iw/parseFloat(ih);

        //console.log(xscale, yscale, pscale, iscale);
        var modefix = 'fix_' + this.mode;
        if (this[modefix]) {
            return this[modefix](this.$w, $p, img, pw, ph, iw, ih, xscale, yscale, iscale);
        }
        
        if (!iscale || !yscale) return;
        
        if (xscale < yscale) {
            th = ph;
        } else {
            tw = pw;
        }

        //console.log(th, tw, img);
        if (!tw) {
            tw = th * iscale;
        } else {
            th = tw / iscale;
        }
        
        //与目标不一样
        if (th != ih || tw != iw) {
            img.height = Math.round(th);
            img.width = Math.round(tw);
            if (tw > pw) {
                $(img).css({
                    'margin-left' : -parseInt((tw-pw)*0.5)
                })
            } else if (th > ph) {
                $(img).css({
                    'margin-top' : -parseInt((th-ph)*0.5)
                })
            }
        }
    },
    
    fix_mode_1_1 : function($w, $p, img, pw, ph, iw, ih, xscale, yscale, iscale) {
        var tw, th;
        
        //横向
        if (iscale >= 1) {
            tw = pw;
            th = tw / iscale;
            
            img.width = tw;
            img.height = th;
        }
        $p.height(img.height);
    }
}

//游记内容部分（图片）
mod.tour = X.reg('Tour', Util.create(Base, {
    view : '#tour_panel',
    
    autoRender : true,
    
    rows : null,
    
    innerViewReady : function(){
        //this.loadPics(this.boxs);
        
        this.getView();
        
        var childs = $('#tour_pics').children();
        var mods = [], $ele;
        for (var i = 0, l = childs.length; i < l; i++) {
            $ele = $(childs[i]) ;
            mods.push({
               top: $ele.offset().top,
               height : $ele.height(),
               loaded : false,
               dom : $ele[0]
            });
        }
        this.mods = mods;
        
        //释放变量 
        mods = $ele = childs = null;
        
        var detectTimer;
        
        var detect = (function(doDetect){
            return function(){
                doDetect();
                detectTimer = null;
            }
        })(Util.getBind(this, 'detect'));
        
        $(win).bind({
            scroll : 
            function(){
               if (detectTimer) 
                    win.clearTimeout(detectTimer);
               
               detectTimer = win.setTimeout(detect, 100);
            }
            ,
            
            resize : detect
        })
        
        var
            view = this.view,
            $hoverObj = null,
            hoverCls = 'hover',
            isMine = this.isMine;
        
        //hover效果
        this.jq().bind({
           mouseover : function(e){
               var
                $target = $(e.target),
                
                //外框
                $frame = $target.closest('div.mod');
               
               //jq.find('div.hover').removeClass('hover');
               
               if ($frame.length && $hoverObj !== $frame) {
                   $hoverObj && $hoverObj.length && $hoverObj.removeClass(hoverCls);
                   $hoverObj = $frame.addClass(hoverCls);
               }
           },
           
           mouseout : function(e){
               var
                $target = $(e.target),
                $related = $(e.relatedTarget),
                $frame = $target.closest('div.mod');

               if ($related.length && (!$frame.length || !$.contains($frame[0], $related[0]))) {
                   $hoverObj && $hoverObj.length && $hoverObj.removeClass(hoverCls);
               }
           }
        });
        /*
        this.debug = (function(){
            
            var $p = $('<div style="top:10px;left:10px;z-Index:100000;position:absolute;width:500px;height:300px;overflow:auto;background:#ccc"></div>');
            $('body').prepend($p);
            
            return {
                log : function(){
                    $p.append('<p>' + $.makeArray(arguments).join(' ') + '</p>');
                }
            }
        })();
        */
        
        detect();
    },
    
    detect : function(){
        var
            mods = this.mods,
            scrollTop = $(document).scrollTop(),
            
            //可视高度
            viewHeight = $(win).height(),
            
            modsToLoad = [],
            
            self = this;
        
        $.each(mods, function(i, mod){
            var top = mod.top,
                end = top + mod.height;
            /*
            self.debug.log(
                i,
                top,
                end,
                scrollTop,
                top >= scrollTop && top <= scrollTop + viewHeight*1.5,
                end >= scrollTop && end <= scrollTop + viewHeight*1.5
            );
            */
            
            if (!mod.loaded && 
                (top >= scrollTop && top <= scrollTop + viewHeight*1.5 ||
                end >= scrollTop && end <= scrollTop + viewHeight*1.5) ) {
                    
                modsToLoad.push(mod);
                mods[i].loaded = true;
            }
        });

        /*        
        $.each(modsToLoad, function(i, r){
            $.each($(r.dom).children(), function(){
                self.loadMod(this);
            });
        });
        */
        
        $(modsToLoad).each(Util.getBind(this, 'loadMod'));
    },
    
    loadMod : function(i, mod){
        var $wrap = $(mod.dom);
        
        $wrap.find('div.mod-in').each(function(){
            new YJ_Image(this, $wrap).load();
        });
    }
}));

X.reg('feeback',Util.create(ui.Base,{
	lock:true,
	hidden:false,
	_hidden:false,
	onContextRelease :function(){
		this.hide();
	},
	closeable:false,
	onViewReady:function(){
		var self = this;
		
		this.fixedOffset();
		$(win).resize(Util.getBind(this,'fixedOffset'));
		
		this.jq('#feeback').click(function(){
			if(self.lock){
				if(self._hidden){
					self.hide();
					$(this).attr('class','btn-fb show');
				} else {
					self.show();
					$(this).attr('class','btn-fb fade');
				}
			}
			return false;
		});
		this.jq('textarea[name="content"]')
			.focusText('请在此填写你的意见或建议','t-focus',this.jq('.fb-txt'),3)
			.keyup(function(){
				if( Util.byteLen(this.value) > 250){
					this.value = Util.byteCut(this.value,250);
					Util.focusEnd(this);
				}
			});
		
		this.jq('#submitBnt').click(function(){
			var input = self.jq('input[name],textarea[name]'),haschecked = false;
			
			var postData='';
			input.each(function(){
				switch(this.type){
					case 'checkbox' : this.checked && ( postData += this.name + '=' + this.value +'&' , haschecked=true); break;
					case 'radio' :  this.checked && ( postData += this.name+ '='  + this.value +'&' , haschecked=true)  ;break;
					case 'hidden' : postData += this.name + '=' + this.value+'&';
				}
				if(this.nodeName == 'TEXTAREA'){
					 postData += this.name + '=' + (this.value=="请在此填写你的意见或建议"?'':this.value);
				}
			});
			if(!haschecked /*&& !self.jq('textarea[name="content"]').val()*/ ){
				var conMgr = X.use('contextMgr');
				conMgr._setCompEvtHandler(self, false);
        		Util.arrayRemove(conMgr.q, self);
    			if(!conMgr.q.length)
    			    $(doc).unbind('mousedown', conMgr._getDocEvtHandler());
				self.contexted = false;
				MB.alert('提示','请选择可选择项',function(){
					self.setContexted(true);
				});
				return false;
			}
			Req.postReq(Req.mkUrl('survey','saveSurvey'),postData,function(r){
				if(r.isOk()){
					self.jq('.fb-done').cssDisplay(1).show();
					self.jq('.fb-done').fadeOut(1800,function(){
						self.hide();
						self.reset();
					});
				} else {
					self.hide();
				}
			});
		});
	},
	reset:function(){
		var input = this.jq('input[name],textarea[name]');
		input.each(function(){
			switch(this.type){
				case 'checkbox':this.checked=false; break;
				case 'radio':this.checked=false; break;
			}
			if(this.nodeName == 'TEXTAREA'){
				this.value = '请在此填写你的意见或建议';
			}
		});
	},
	fixedOffset:function(){
		var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
		var fix = (clientHeight - this.jq().height()) / 2;
		fix = fix > 0 ? fix :0 ;
		this.jq().css('top', fix);
	},
	show : function(){
		var self = this;
		this.lock = false;
		this.jq().animate({right:0},400,function(){
			self.setContexted(true);
			self.lock = true;
			self._hidden = true;
		});
	},
	hide : function(){
		var self = this;
		this.lock = false;
		this.jq().animate({right:-192},400,function(){
			self.setContexted(false);
			self.lock = true;
			self._hidden = false;
		});
	}
}));

//表单输入框提示文字
X.reg('InputLab',Util.create(Base,{
	items : [],
	autoRender : true,
	onViewReady : function(){
		this.items.each(function(i){
			var $t = $(this);
			$t.click(function(e){
				if(this.value == $t.attr('lab')) this.value = '';
			}).blur(function(e){
				if(this.value == '') this.value = $t.attr('lab');
			}).focus(function(){
				if(this.value == $t.attr('lab')) this.value = '';
			});
		});
	}
}));

//限制输入数量 
//X.use('InputLimit',{items : [{obj:info[0],len:100},{obj:info[1],len:1500}]});
X.reg('InputLimit',Util.create(Base, {
	items : [],
	autoRender : true,
	onViewReady : function(){
		$.each(this.items,function(i,o){
			$(o.obj).keydown(function(e){
				if(Util.byteLen(this.value)>o.len){
					this.value = Util.byteCut(this.value,o.len);
				}
			}).blur(function(){
				if(Util.byteLen(this.value)>o.len){
					this.value = Util.byteCut(this.value,o.len);
				}
			})
		});
	}
}))


//分页
/*X.use('Page',{
	total : 100,
	curPage : 1,
	appendTo : '#page',
	loadData : function(){}	
})
*/

X.reg('Page',Util.create(Base, {
	autoRender : true,
	actionMgr : TRUE, 
	total : 150,
	pageSize : 10,
	curPage : 1,
	totalPage : 10,
	begin : 1,
	limit : 5,
	lock : false,
	delayed : true,
	refurbish : true,
	appendTo : 'body',
	id : '',
	view : 'Page',
    onactiontrig : function(e) {
		switch (e.data.e) {
			case 't':
				this.curPage = parseInt(e.get('n'));
				if(!this.lock)
					this.explain(e);
			break;
		}
	},
	onViewReady : function(){
		this.total = Number(this.total);
		if(this.getCount){
			this.getCount();
		}else{
			this.start();	
		}
	},
	
	explain : function(e){
		this.curPage = Number(e.get('n'));
		this.lock = 1;
		if(this.refurbish){		
			callBack = Util.bind(this.create, this);
			this.loadData(this.curPage , callBack);		
		}
	},
	
	loadData : function(page, callBack){
		callBack();
	},
	
	start : function(){
		this.totalPage = Math.ceil(this.total/this.pageSize);
		this.create();	
	},
	
	remove : function(){
		this.jq().remove();
	},
	
	create : function(){
		this.lock = 0;
		var mid = Math.round(this.limit/2) -1;
		var big = this.totalPage, leftLine = false, rightLine = false;
		
		if(big <= this.limit){
			this.begin = 1;
		}else if(this.curPage + mid < this.totalPage){
			if(this.curPage - mid > 1){
				leftLine = true;
				this.begin = this.curPage - mid;
				big = this.curPage + mid;
			}else{
				this.begin = 1;
				big = this.limit
			}
			if(this.curPage + mid +1 < this.totalPage)
				rightLine = true;
		}else{
			if(this.totalPage<this.limit){
				this.begin = 1;
			}else{
				this.begin = this.totalPage - this.limit +1;	
				leftLine = true;				
			}
			big = this.totalPage;
		}
		this.pageModel(big, leftLine, rightLine);
	},
	
	pageModel: function(big, leftLine, rightLine){
		var pageHtml = [], first = true;
		if(this.curPage == 1){//上一页
			pageHtml.push('<span class="prev prev-disable">上一页</span>');			
		}else{
			pageHtml.push('<span class="prev"><a href="#" rel="e:t,na:1,n:'+(this.curPage-1)+'">上一页</a></span>');
			if(this.begin != 1) pageHtml.push('<span><a href="#" rel="e:t,na:1,n:1">1</a></span>');
		}
		for(var i = this.begin; i<=big; i++){
			if(first && leftLine) pageHtml.push('<span>...</span>'); 
			first = false		
			if(i == this.curPage) pageHtml.push('<span class="nullCur">'+i+'</span>');
			else pageHtml.push('<span><a href="#" rel="e:t,na:1,n:'+i+'">'+i+'</a></span>');
	
		}
		
		if(rightLine){//下一页
			pageHtml.push('<span>...</span>');				
		}
		

		if(this.totalPage == this.curPage){
			pageHtml.push('<span class="next next-disable">下一页</span>');			
		}else{
			if(big != this.totalPage)pageHtml.push('<span><a href="#" rel="e:t,na:1,n:'+this.totalPage+'">'+this.totalPage+'</a></span>');	
			pageHtml.push('<span class="next"><a href="#" rel="e:t,na:1,n:'+(this.curPage+1)+'">下一页</a></span>');
		}
		
		this.jq().html(pageHtml.join(''));		
	}
}))

//选择用户
X.reg('selectUser',Util.create(Base, {
	items : [],
	autoRender : true,
	actionMgr : TRUE, 
	setCls : 'cur',
    onactiontrig : function(e) {
		switch (e.data.e) {
			case 'c':
				this.check(e);
			break;
		}
	},
	onViewReady : function(){
		this.jq('li').mouseover(function(e){
			var $t = $(this);
			if(!$t.hasClass('cur')){
				$t.addClass('hover');
			}
		}).mouseout(function(e){
			$(this).removeClass('hover');
		});	
	},
	
	check : function(e){

		var $t = $(e.src), p = $t.parent(), checked = false//是否选中;
		if(p.hasClass('cur')){
			p.removeClass('cur');
		}else{
			if(this.beforeCheck)
				if(this.beforeCheck(e) == false) return;
			p.addClass('cur');
			checked = true;
		}
		this.afterCheck && this.afterCheck(checked, e);
	},
	
	del : function(e){
		var u = e.get('u');
		this.jq('li[rel^=u:'+u+']').removeClass('cur');
	}
}))



//tab 切换
X.reg('SwitcherExt',Util.create(Base, {
	autoRender : true,
	actoinObj : '',//点击对象
	tag : 'a',
	items : [],
	cls : 'cur',
	cur : 0,
	onViewReady : function(){
		var self = this;
		this.cur = this.items[this.cur];
		$('#'+this.actoinObj).click(function(e){
			e.preventDefault();
			if(e.target.tagName.toLowerCase() == self.tag){
				var news = $(e.target), t = news.attr('rel');
				if(t){
					if(self.setTab(news)){
						self.toPage(Util.parseKnV(t));
					}
				}
			}
		})
	},
	
	setTab : function(news){
		var old = $('#'+this.actoinObj).find(this.tag+'.'+this.cls);
		if(old.attr('rel') == news.attr('rel')) return false;
		old.removeClass();
		news.addClass(this.cls);
		return true;
	},
	
	getJq : function(id){
		var jcur = this.jq(id);
		if(jcur.length == 0) jcur = $(id);
		return jcur;
	},
	
	toPage : function( p ){
		var data = this.items[p.s];			
		//显示列表
		var old = this.getJq(this.cur.id).hide();
		this.cur = data;
		var news = this.getJq(data.id);
		if(news.length == 0){
			this.getPart(data);
		}else{
			news.show();
		}
		
	},
	
	getPart : function( data ){
		
	}
	
}));

X.reg('LoadPage', Util.create(Base, {
	autoReader : true,
	parent : '',
	ui : '',
	cfg : '',
	pageSize : 10,
	onViewReady : function(){
		var d = this.cfg.data, uid = d.uid || getCfg('uid'), state = d.state, parent = this.parent, pageSize = d.count || this.pageSize, type = d.type;
		var cursor = d.cursor;
		function setupPage(param){
			X.use('Page',{
				total : param.total,
				pageSize : pageSize,
				curPage : 1,
				appendTo : parent,				
				id : 'pagePart_'+param.state,
				loadData : function(page, fn){
					var self = this;
					Req.getFootMark({uid:uid, state:param.state, cursor:(page-1)*pageSize}, function(r){
						self.lock = false;											
						if(r.isOk()){
							fn && fn();//修改分页符
							var d = r.getData();
							setTimeout(function(){
								parent.find('#footmark_'+param.state).replaceWith(d.html);
								hover();	
								if(getCfg('uid'))
									X.use('usersCard',{items:parent.find('#footmark_'+param.state).find('.user_card')});								
								X.use('SetScroll').init({toTop : parent.offset().top - 45});
								//setScroll(parent.offset().top);
							},200);	
						}
					})
				}	
			});
		};
		if(d.total>pageSize)
			setupPage({total:d.total, state: d.state});
			
		function hover(){
			parent.find('ul>li').hover(function(e){
				$(this).find('div.operate>div').cssDisplay(1);
			},function(e){
				$(this).find('div.operate>div').cssDisplay(0);
			});
		}
		
		hover();
		
		X.use('SwitcherExt', {					
			items :[{id:'footmark_0',state:0},{id:'footmark_1',state:1},{id:'footmark_2',state:2},{id:'footmark_3',state:3}],
			actoinObj : 'markParent',
			setTab : function(o){
				var p = o.parent(), s = p.find('span'), oldRel = s.attr('rel'), oparam = Util.parseKnV(oldRel), newRel = o.attr('rel'), nparam = Util.parseKnV(newRel) ;
				s.replaceWith('<a href=# rel="'+oldRel+'">'+s.text()+'</a>');		
				parent.find('#pagePart_'+oparam.s).hide();
				parent.find('#footmark_'+oparam.s).hide();	
				o.replaceWith('<span rel="'+o.attr('rel')+'">'+o.text()+'<em></em></span>');	
				return true;
			},
			
			getPart : function(data){
				var footmark = parent.find('#footmark_'+data.state);
				if(footmark.length){
					footmark.show();
					parent.find('#pagePart_'+data.state).show();
				}else
					Req.getFootMark({uid:uid, state:data.state, cursor: 0}, function(r){						
						if(r.isOk()){							
							var rd = r.getData();
							parent.find('#footmark>div[id^=foot]:visible').hide();
							parent.append(rd.html);
							if(getCfg('uid'))
								X.use('usersCard',{items:parent.find('#pagePart_'+data.state).find('.user_card')});							
							hover();
							X.use('SetScroll').init({toTop : parent.offset().top - 45});
							if(rd.total>pageSize)
								setupPage({total:rd.total, state: rd.state});
						}
				})
			}
		}); 
	
	}

}));

//轮播左右连续滚动
//Xwb.use('runModule',{view:$('#runBox')[0]})
X.reg('runModule', Util.create(Base, {
	autoRender : true,
	tag : 'li',
	timer : null,
	items : 8,
	delay: 100,
	way : 'left',
	type : 1,
	onViewReady : function(){		
		this.maxWidth = parseInt(175)*(this.items-5);
		var self = this;
		this.jq('ul').mouseover(function(e){
			self.stop();
		}).mouseout(function(){
			self.start();
		});
		this.jq('#next').click(function(e){
			e.preventDefault();
			self.way = 'right';
		})
		this.jq('#prev').click(function(e){
			e.preventDefault();
			self.way = 'left';
		})
		
		this.start();
	},
	
	start : function(){
		this.effect();
	},
	
	stop : function(){
		clearTimeout(this.timer);
		this.timer = null;
	},
	
	setWay : function(way){
		this.way = way;
	},

	effect : function(){
		var jq  = this.jq('ul');
		function to(px,p){
			p == 'left' ? jq.css('marginLeft',px-1+'px')
			: jq.css('marginLeft',px+1+'px');
		}
		var way = this.way, px = parseInt(jq.css('marginLeft'));
		if(way == 'left'){
			if((0-this.maxWidth)< px)
				to(px,'left');
			else 
				to(px,this.way = 'right'&&'right');
		}
		if(way == 'right'){
			if(px<0)
				to(px,'right');
			else
				to(px,this.way = 'left'&&'left');
		}
		this.timer = setTimeout(Util.bind(this.effect, this),2);
	}
}))

//路书编辑、纠错
X.reg('editGuide', function( cfg ){
	return X.use('Dlg',{
		cs : 'win-forward',
    	appendTo : "body",
		cs : 'win-form win-fixed hidden',
		title : cfg.title,
		paragraph : cfg.paragraph,
		titCls : 'x-bg',
		destroyOnclose : true,
		param : {},
    	dlgContentHtml : 'GuideEditForm',
		closeable : true,
		onViewReady : function() {
		    $.extend( this.param, cfg );
			var self = this;
			self.jq("#btn-Confirm").click(function(){
				var v = self.jq('textarea').val();
				if(!v) {
				    MB.error('提示','内容不能为空');
					return false;
				}
				self.param['content'] = v;
				Req.editSpotsGuide( self.param, function(e){
				    if(e.isOk()){
						var msg;
					    self.title === "我来纠错" ?
						    msg = "内容提交成功，你将在管理员审核后看到更新后的内容！<br />审核通过会获得“眼明手快”勋章。<br />成功纠错5次以上更能获得“见多识广”勋章，继续努力吧！" : 
						    msg = "内容提交成功，你将在管理员审核后看到更新后的内容！<br />审核通过会获得“眼明手快”勋章。<br />成功提供资料5次以上更能获得“见多识广”勋章，继续努力吧！"
						MB.alert("提示",msg);
					}else MB.alert(e.getError());
					self.close(1);
				}); 
			});
			self.jq("#btn-Cancel").click(function(){ self.close(); })
		}
	});
})
//spots.nav页面，切换省份
X.reg( 'provSelect', function( cfg ){

    var inst = $.extend({}, mod.PostBase);
    $.extend(inst, {
    	cs : 'win-tour-place',
    	appendTo : "body",
    	contentHtml : 'sitesTpl',
		boxOutterHtml : '<div class="arrow"></div>',
		contextable : true,
		locationData : null,  //位置的数据，由后台管理，异步获取
		
		triggerBtn : '#btnChProv', //页面上调用该控件的按钮或链接
		innerSiteBox : '#sites',
		
		hcls : 'cur',   //选中样式
		curSelected : cfg.prov_id,  // cfg.prov_id 为当前的省份id

		onViewReady : function( cfg ){
		    var tthis = this, 
			    $sitebox = this.innerSiteBox = this.jq(this.innerSiteBox);
			if( !tthis.locationData ){
		    	Req.getProvince( function(e){
			   		if(e.isOk){
			       		tthis.locationData = e.getData().list;
						tthis.setLocationList();
				    }
					else {
					    MB.error('','获取数据失败，请重试', function(){
					        tthis.close(1);
					    })
					}
			   	})
			};
			$sitebox.delegate('a', 'click', function(e){
				$sitebox.find('a.' + tthis.hcls ).removeClass( tthis.hcls );
				id = tthis.curSelected = this.getAttribute('data-id');

				var $triBtn = $(tthis.triggerBtn);
				$triBtn.prev("strong").html( this.innerHTML );
				$triBtn.replaceWith( '<span rel="e:chProv,prov_id:'+ id +'" id="btnChProv">切换省份</span>' );
				tthis.close();
				location.href = Req.mkUrl('spots','nav') + '&id=' + id;
			});
		},
		setLocationList : function(){
		    var alist = [], 
			    pdata = this.locationData, 
				cid = this.curSelected;
            //返回的数据结构为 [{"id":1,"name":"\u65b0\u7586"},{"id":2,"name":"\u9ed1\u9f99\u6c5f"},.....]
			for( var i=0, prov; prov=pdata[i]; i++) {
			    var cid = this.curSelected || -1;
				if( cid == prov.id )
				    alist.push('<a href="javascript:;" class="'+this.hcls+'" data-id="'+ prov.id +'"  >' + prov.name + '</a>');
			    else alist.push('<a href="javascript:;" data-id="'+ prov.id +'"  >' + prov.name + '</a>');
			}
		    this.jq('#sites').html(alist.join(''));
		}
	})
	inst = X.use( 'Box', inst);
    X.reg( 'provSelect', inst, true);
    return inst;
});

/**
 * @class Xwb.mod.notice
 * 消息提示浮层
 * @extends Xwb.ui.Box
 * @singleton
 */
 
X.reg('notice', function( cfg ){
	var limitTop = 29;
	X.use('Box', {
    	cs:'win-fixed win-notice',	
		contentHtml : 'NoticeLayer',
        appendTo : document.body,
		msgUrl : Req.mkUrl('center','message'),
		youjiUrl : Req.mkUrl('center','',{org:0}),
		friFeedUrl : Req.mkUrl('message'),
        closeable:true,
		notices : ['msg', 'youji', 'friFeed'],
		hidden : true,
		onViewReady : function(v){
			// 监听轮询事件
			this.jq().attr('id','noticeArea');
			getCfg('rightTopFloat').push('#noticeArea');
			X.use('keepTop').init(this.jq(), limitTop, true);	
			X.on('public.unread', Util.bind(this.unreadLoad, this));
		},
		setNotice : function(lists){
			if(lists === 0){
				var ns = this.notices, lists = {};
				for(var i=0,j=ns.length;i<j;i++)
					lists[ns[i]] = 0;
			}
			var show = false;
			for(var k in lists){
				var v = Number(lists[k]), obj = this.jq('#'+k);
				if(obj.length == 0) continue;
 				obj.find('#n').text(v);
				if(v>0){
					show = true;
					if(k == 'msg' || k=='youji')obj.cssDisplay(1);
				}else{
					obj.cssDisplay(0);
				} 
			}
			
			this.display(show);
			return show;
		},
		
		onClsBtnClick : function(e){
			e.preventDefault();
			ui.Base.prototype.onClsBtnClick.call(this);
			//var n = Number(this.jq('#n').text());
			//if(n>0){
				this.setNotice(0);
				$('#headMessage').text(0).parent().cssDisplay(0);
				Req.clearUnread(function(){});
			//}
		},		
		
		unreadLoad : function(e){
			if(e.isOk()){
				var lists = e.getData();
				var show = this.setNotice(lists);
				//if(show){
					var n = lists['msg'];
					if(n>0){					
						$('#headMessage').text(n).parent().cssDisplay(1);
						//this.display(1);
						
						
					}else{
						$('#headMessage').text(0).parent().cssDisplay(0);
						//this.display(0);
					}
					
				//}
				if(lists['friFeed']>0)
					$('#friendMsgs').text(lists['friFeed']).parent().cssDisplay(1);
				else
					$('#friendMsgs').text(0).parent().cssDisplay(0);
				
				this.setTitleNotice( n );
			}
		},
		//新消息 窗口标题栏通知
		setTitleNotice : function(n){
			var titText = document.title,
			    titFilterText = titText.substring( titText.indexOf(']') + 1 );
			n>0 ? document.title = '[你有'+n+'条新消息]'+ titFilterText : document.title = titFilterText;
		}
    }).display(0);
});

	
//举报
X.reg('Report',Util.create(ui.Box,{
	contentHtml:'Report',
	cs:'win-form win-form-s1 win-fixed',
	title:'举报',
	destroyOnClose:true,
	closeable:true,
	mask:true,
	maxLen:250,
	onViewReady:function(){
		var self = this;
		this.jq('#xwb_ok').click(function(){
			var data = {type:0};
			self.jq('input:checked').each(function(){
				data.type += + $(this).val();
			});
			data.content = Util.trim(self.jq('#content').val());
			if(data.type == 0){
				MB.alert('提示','请选择举报类型！');
				return;
			}
			if(data.content == ''){
				MB.alert('提示','请输入举报说明！');
				return;
			}
			self.sendData(data);
			return false;
		});
		self.jq('#content').keyup(function(){
			var val = $(this).val();
			if(Util.byteLen(val) > self.maxLen)
				$(this).val(Util.byteCut(val,self.maxLen));
				Util.focusEnd(this);
		});
	},
	Report:function(t){
		switch(t){
			case 'y':
				return Req.YReport
			case 'c':
				return Req.CReport
			case 'q':
				return Req.QReport
			case 'a':
				return Req.AReport
		}
	},
	sendData:$.noop
}));

//图片延迟加载
X.reg('lazyLoadPic', function( proto ){
    var llp = Util.create();
	llp.prototype = $.extend({
	    //可配置项
	    lazyImgBoxs : 'div.img-wrap', //默认的选择符
		enableSyncLimit : FALSE,   // 是否开启同步载入图片数限制设置
		syncLimit : 6,    //同时载入图片数限制，最多同时加载6个
		
		loadingNum : 0, //正在载入的图片个数
		jamSeq : [],    //堵塞序列
		
        getOffsetTop: function ( elem ){
            var sTop = elem.offsetTop;
            while (elem = elem.offsetParent)
                sTop += elem.offsetTop;
            return sTop;
        },
		
		lazyLoad: function(){
			var self = this,
				imgboxs = self.lazyImgBoxs;
			//避免事件触发过于频繁	
			//window.onscroll = null;// or $(doc).unbind("scroll", self._lazyLoad );  
			
			if( imgboxs.length <= 0 ){
			    $(win).unbind("scroll", self._lazyLoad );
				return  ;
			}
			var viewH = Util.getClientHeight(); //浏览器可视窗口高度
			    scrH = $(document).scrollTop();   //浏览器滚动的高度
			for (var i = 0; i < imgboxs.length; ) {
			    var cur = imgboxs[i],
				    t = this.getOffsetTop( cur );
				if ( t > scrH - 600 && t < scrH + viewH + 600 ) {	//预载入上下大约一屏的图片
					if(self.enableSyncLimit){
						if( self.loadingNum < self.syncLimit)
						    self.insertHandleImg( cur, cur.getAttribute("src") );
						else 	
						    self.jamSeq.push( cur );
					}
                    else	
					    self.insertImg( cur, cur.getAttribute("src") );
					imgboxs.splice( i, 1 );
				}
				else i++;
			}
			//延迟200ms再绑定
			//setTimeout( function(){ $(doc.body).bind("scroll", self._lazyLoad );  /*window.onscroll = self._lazyLoad;*/ }, 200);  
		},
		insertImg : function( elm, src ){       //插入图片
            var img = doc.createElement("IMG");
			img.style.cssText = elm.style.cssText;
			img.setAttribute('alt', elm.getAttribute('title') || elm.getAttribute('alt'));
            elm.removeAttribute('title');
			elm.removeAttribute('alt')
			img.src = src;					
			elm.appendChild( img );
			return img;
		},
		insertHandleImg : function( elm, src ){  //插入图片，并监听onload事件
		    var self = this;
		    var img = self.insertImg( elm, src );
			if (img.complete) { // 如果图片已经存在于浏览器缓存
				return;
			}
			self.loadingNum++;
		    img.onload = function(){
				var elm = self.jamSeq.shift();
			    if( self.loadingNum < self.syncLimit &&  elm ){  //限制同时同时下载
				    self.insertHandleImg( elm, elm.getAttribute("src") );
				}
				self.loadingNum--;
			}
		},
	    init: function(){
		    var t = this.lazyImgBoxs = $(this.lazyImgBoxs );
			if( !t.length  )
				return false;
			
			this.lazyLoad();  //预处理
			this._lazyLoad = Util.bind( this.lazyLoad, this );
			//window.onscroll = this._lazyLoad;
			$(win).bind("scroll", this._lazyLoad); //添加事件
		}
	}, proto);
	return new llp();
});

//异步加载googleMap
X.reg('LoadGoogleMap', {
	initUI : function(opt, obj, foots, fn, callBack){
		$('head').append('<script src="http://maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>'); 
		win.initialize = fn || function() { 
			var g = Util.ns('google.maps');
			if(g){					
				//加载完成后再
				obj.ui = new X.mod.footMarkMine(opt);
				//触发onViewReady
				obj.ui.getView();
				obj.ui.initFoots(foots);
				callBack && callBack();
			}		
		}
	}
});

//异步加载BaiduMap
X.reg('LoadBaiduMap', {
	initUI : function(opt, obj, foots, fn, callBack){
		$('head').append('<script src="http://api.map.baidu.com/api?v=1.2&callback=initialize" type="text/javascript"></script>'); 
		win.initialize = fn || function() { 
			opt.foots = foots
			var ui = X.use('ExtBaiduMap', opt).display(1);
			obj.ui = ui;
			callBack && callBack();	
		}
	}
})

//浮层保持一定高度
X.reg('keepTop', {	
	init : function(view, top, allBrowser){
		this.view = view;
		this.top = top;
		//if(!X.util.ie6) this.keepTopNormal();
		//else 
		if(X.util.ie6){
			this.keepTopIE6();	
		}else if(allBrowser) this.keepTopNormal();
	},

	keepTopNormal : function(){
		var $tip = this.view, self = this, top = this.top;
		function fixPosition() {			
			var scTop = $(document).scrollTop();
			if (scTop > top) {				     
				$tip.css('top','0');
			} else {
				//console.log(top-scTop);
				$tip.css('top',top-scTop);
			}
		};
		$(win).scroll(fixPosition);
		$(win).resize(function(){
			fixPosition();   
		});
		fixPosition();//先调用一次调整位置
	},
	
	keepTopIE6 : function() {
		var self = this;
		$(win).scroll(Util.bind(this.readySetPosition,this));
		$(win).resize(function(){
			self.readySetPosition(1);   
		});
		this.readySetPosition();//先调用一次调整位置
	},
	
	readySetPosition : function(){
		//this.view.cssDisplay(0);
		var self = this;
		clearTimeout(self.topFlag);
		this.topFlag = setTimeout(function(){
			self.setPosition();
		},100); 
	},
	
	setPosition : function(){
		var $tip = this.view, top = this.top;
		var scTop = $(document).scrollTop();
		if (scTop > top) {						
			$tip.css('top',scTop+'px');
		} else {
			$tip.css('top',(top-scTop)+'px');
		}				
		//$tip.cssDisplay(1);
	}
})

//滚动条滑动到指定点
X.reg('SetScroll', {
	obj : $(document),
	times : 1,
	starStep : 45,
	delTimes : 100,
	delBase : 0.2,
	prev : 0,

	init : function(cfg){
		cfg && $.extend(this,cfg);
		if(this.obj.scrollTop() > this.toTop)
			this.scrollCut();
		else
			this.scrollAdd();
	},
	
	scrollCut : function(){
		var h = this.starStep - this.times*this.delBase, sTop = this.obj.scrollTop();
		if(sTop > this.toTop){
			if(sTop - this.toTop < h) h = sTop - this.toTop;
			$(document).scrollTop(sTop - h);
			this.times < this.delTimes && this.times++;
			setTimeout(Util.bind(this.scrollCut,this), 1);
		}
	},
	
	scrollAdd : function(){
		var h = this.starStep - this.times*this.delBase, sTop = this.obj.scrollTop();
		if(this.toTop > sTop){
			if(this.prev == sTop) return;
			if(this.toTop - sTop < h) h = this.toTop - sTop;
			this.prev = sTop + h;
			$(document).scrollTop(sTop + h);
			this.times < this.delTimes && this.times++;
			setTimeout(Util.bind(this.scrollAdd,this), 1);
		}
	}
})


//增加经验或者游币
X.reg('CoinExperience', function(cfg){
	return Xwb.use('Tip', {
		cs:'win-fixed win-success',
		contentHtml :'<p id="notice"></p>',
		appendTo:'body',
		destroyOnClose :true,
        first : true,
		timeoutHide : 2000,
		beforeShow : function(){
			ui.Tip.prototype.beforeShow.call(this);
			this.jq('#notice').html(cfg.notice);
		},
		afterHide : function(){
			ui.Tip.prototype.afterHide.call(this);
			if(!this.first){
				this.close();
				cfg.cb && cfg.cb();
			}else{
				this.first = false
			}
		}
		
     }).display(1); 
});


//勋章
X.reg('MedalBox', Util.create(Base,{
	trigEvent : 'mouseover'
	,tipFloat : ''
	,cache : null
	,delayTime : 100
	,isOnready : false	
	,init : function(opt){
		Util.extend(this,opt,true);
		var self = this;
		opt.items.bind(this.trigEvent,function(e){
			if(self.curObj != this){
				$(this).data('onover',true);				
				var obj = this;
				setTimeout(function(){self.delayShow(obj,e)},self.delayTime);	
			}			
		}).mouseout(function(){
			if(self.curObj == this)
				self.setHideTimer();
			$(this).data('onover',false);
		});		
	}
	
	//延迟显示明片
	,delayShow : function(obj,e){
		if($(obj).data('onover') == true){
			this.event = e;
			this.clearHideTimer();
			if(this.curObj != obj){
				if(this.tipFloat){
					this.tipFloat.display(0);
				}					
				this.curObj = obj;		
				this.isOnready = false;				
				this.getMedalData();				
			}
		}
	}
	
	,getDataFromCathe : function(v){
		if(this.cache){
			return this.cache[v];			
		}
		return '' ;
	}
	
	,getMedalData : function(){
		var v = Util.parseKnV($(this.curObj).attr('rel'));
		this.uid = v.u;
		var data = this.getDataFromCathe(v.k);		
		if(data!==''){
			this.isOnready = true;
			this.showFloat(data);
		}else{
			var isNull = v.k? true : false;
			this.showFloat('');
			isNull && this.getDataFromAjax(v.k);
		}
	}
	
	,getDataFromAjax : function(k){
		var self = this;
		Req.getMedalInfo(this.uid,function(e){		
			if(e.isOk()){
				self.cache = e.getData();
				if(self.display()){				
					self.isOnready = true;
					self.curData = self.getDataFromCathe(k);
					self.tipFloat.setContent();
				}
			}else{
				self.userData = '<div class="load-fail">'+e.getMsg()+'</div>';
				if(self.getCurKey() == self.getCurKeyByEncode(opt))
					self.tipFloat.setContent();
			}
			self.tipFloat.resetOffset();// 重新定位浮层高度			
		});
		
	}
	
	,showFloat : function(data){
		this.curData = data;
		if(this.tipFloat) {			
			this.tipFloat.display(1);
		}else{
			this.createBox(data);
		}
	}
	
	,setHideTimer : function(){
		this.hideTimeout = setTimeout(Util.getBind(this, 'onTimerHide'), this.delayTime);
	}
	
	,onTimerHide : function(){
        this.tipFloat.display(FALSE);
    }
	
	,clearHideTimer : function(){
		if(this.hideTimeout){
			clearTimeout(this.hideTimeout);
			this.hideTimerId = FALSE;
		}
	}
	,createBox : function(data){
		var self = this;
 		this.tipFloat = Xwb.use('Tip', {
			cs:'win-medal-info',
			contentHtml : 'Loading',
			boxOutterHtml : '<div class="arrow bg-all"></div>',
			appendTo : document.body,
			autoHide : false,
			stayHover : true,
			init : false, //是否初始化了
			isHide : true,
			destroyOnClose : false,
			contextable: false,    
 			onViewReady : function( v ){
			}, 			
			beforeShow: function(d){
				this.init = true;
			    //在这里要处理 数据和位置
				this.setContent();	
				var cls = this.setOffset();
				this.setTipCls(cls);
				ui.Tip.prototype.beforeShow.call(this);
			},
			
			beforeHide : function(){			
				this.isUfls	= false;			
				if(this.init) self.curObj = '';
				self.curKey = '';
				this.isHide = true;
				ui.Tip.prototype.beforeHide.call(this);
			},
			clearHideTimer : function(){
				self.clearHideTimer();
			},
			setHideTimer : function(p){
				if(this.isHide){				    
					self.setHideTimer();
				}
			},			
			setContentBefore : function(){
				var html = this.get_Content();		
				if(html){
					this.jq('.win-box').html(html);
				}
			},
			setContent : function(){
				this.setContentBefore();
			},			
			get_Content : function(){
				if( self.curData){
					if(typeof self.curData == 'object'){//处理浮层位置
						if(typeof self.curData.info == 'string'){
							self.curData.info = eval("("+self.curData.info+")");
							self.curData.info.pic = getCfg('basePath')+self.curData.info.image;
							self.curData.info.url = Req.mkUrl('profile','medal',{id:self.uid});
						}
						return T.parse(T.get('medalBox'),self.curData.info);
					}else{
						return self.curData;
					}
				}else{
					return '<div id="xweibo_loading" class="loading"></div>';
				}		
			},
			
			getContent : function(){
				return this.jq('.win-box').html();
			},
			//重新定位浮层高度
			resetOffset : function(){
				var cls = this.getView().className;		
				if(Util.ie6){
					this.getView().className = cls; 
				}				
				if(cls.indexOf('arrow-b')>-1 || cls.indexOf('arrow-l')>-1){
				    var curA = $(self.curObj), coff = curA.offset(), height = this.jq().height();
					this.offset({top:coff.top - height});
				}
			},
	
			//计算显示位置
			setOffset : function(){
				var height = this.jq().height()
				, bodyWidth = 265   //主体宽度，箭嘴左右宽度
				, curA = $(self.curObj)
				, off = curA.offset()
				, toLeft = off.left > 265
				, info = this.browseInner()// 总高
				, limitTop = 160
				, left = 0
				, top = 0
				, cls = ''
				, mh = curA.width();	
				
				if(off.top - limitTop > info[2]){
					cls = toLeft?'win-pop win-medal-info arrow-b':'win-pop win-medal-info arrow-l'; 
					//左右是否
					top = off.top - height;	
					left = toLeft ? (off.left-mh/2 - bodyWidth) : (off.left - 25);
				}else{//在下面显示器
					//cls = 'win-pop win-medal-info arrow-r';
					cls = toLeft?'win-pop win-medal-info arrow-r':'win-pop win-medal-info arrow-t'; 
					top = off.top + curA.height();
					//left = off.left-mh/2 - bodyWidth;
					left = toLeft ? (off.left-mh/2 - bodyWidth) : (off.left - 25);
				} 
				
			    this.offset({top:top,left:left});
				return cls;
			},
			
			setTipCls : function(cls){
				this.getView().className = cls;
			},
			
			browseInner : function(){
			   var pageWidth = win.innerWidth,pageHeight = win.innerHeight;
				if (typeof pageWidth != "number"){
					pageWidth = document.documentElement.clientWidth || document.body.clientWidth;
					pageHeight = document.documentElement.clientHeight || document.body.clientHeight;
				}
				var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
				return [pageWidth, pageHeight, scrollTop];
			}
		});
		this.tipFloat.display(1); 
	} 

}));

//微博时间转义
X.reg('getTimeString', { fn: function(t){
	var s = (Math.round(+new Date)/1000 - t) 
	if(s <= 0){
		return '1秒前';
	}
	if(s < 60){
		return Math.round(s)+'秒前';
	}
	if(s < 3600){
		return Math.round(s/60)+'分钟前';
	}
	if(s < 86400){
		return Math.round(s/3600)+'小时前';
	}
	return Math.round(s/86400)+'天前';
	}
});	

/**
 * 昵称提示浮层
 */
X.reg('usersCard', Util.create(Base, {	
	//缓存
	cathe : {}	
	,items : []	
	,loading : false	
	,curObj  : '' //mouseon对象	
	,isOnready : false	
	,trigEvent : 'mouseover'	
	,tipFloat : ''	
	,curKey : ''	
	,hideTimeout : ''	
	,delayTime : 600
	,event : ''
	
	//从缓存取数据
	,getDataFromCathe : function(opt){
		if(opt.u == 100){
			return {sinaid : opt.sid, img : decodeURIComponent(opt.i), url:'http://weibo.com/u/'+opt.sid,nick:opt.n};
		}
	
		var key = this.getCurKey(opt);	
		return this.cathe[key] || '';
	}
	
	,getCurKey : function(opt){
		if(opt)
			return opt.n?('name@'+ opt.n):('id@'+ opt.u);
		var v = Util.parseKnV($(this.curObj).attr('rel'));
		return this.getCurKey(v);
	}
	
	,getCurKeyByEncode : function(opt){
		return opt.name?('name@'+ opt.name):('id@'+ opt.id);
	}
	
	,init : function(opt){
		Util.extend(this,opt,true);
		var self = this;
		
		this.isRecommend = $.inArray(this.page,['search.recommend','search.starChildSortList'])!=-1?true:false;
		opt.items.bind(this.trigEvent,function(e){
			if(self.curObj != this){
				$(this).data('onover',true);				
				var obj = this;
				setTimeout(function(){self.delayShow(obj,e)},self.delayTime);	
			}			
		}).mouseout(function(){
			if(self.curObj == this)
				self.setHideTimer();
			$(this).data('onover',false);
		});		
	}
	
	//延迟显示明片
	,delayShow : function(obj,e){
		if($(obj).data('onover') == true){
			this.event = e;
			this.clearHideTimer();
			if(this.curObj != obj){	
				if(this.tipFloat){
					this.tipFloat.display(0);
				}					
				this.curObj = obj;		
				this.isOnready = false;				
				this.getPeopleData();				
			}
		}
	}

	,setHideTimer : function(){
		this.hideTimeout = setTimeout(Util.getBind(this, 'onTimerHide'), this.delayTime);
	}
	
	,onTimerHide : function(){
        this.tipFloat.display(FALSE);
    }
	
	,clearHideTimer : function(){
		if(this.hideTimeout){
			clearTimeout(this.hideTimeout);
			this.hideTimerId = FALSE;
		}
	}
 	
	,getPeopleData : function(){
		var v = Util.parseKnV($(this.curObj).attr('rel'));
		//if(v.t){
		    var data = this.getDataFromCathe(v);			
			if(data!==''){
				this.isOnready = true;
				this.curKey = this.getCurKey(v);
				this.showFloat(data);
			}else{
				var opt = {};
				var isNull = true;
				opt.id = v.u;
				isNull = opt.id?false:true;
				this.showFloat('');
			    !isNull && this.getDataFromAjax(opt);
			}
		//}	
	}
	
	//网络请求数据
	,getDataFromAjax : function(opt){	
		var self = this;
		Req.getUserInfo(opt.id,function(e){		
			if(e.isOk()){
				var isTrue = self.checkIsSelf(e.getData());
				var newData = self.filterData(e.getData());
				self.curKey = self.getCurKeyByEncode(opt);
				self.addCathe(self.curKey,newData);
				if(self.display()){
					if(isTrue === true){//当前用户				
						self.userData = newData;
						self.tipFloat.setContent();					
						self.isOnready = true;
						self.tipFloat.resetPosition();// 重新定位浮层高度
					}else{//数据不是当前用户
						self.curKey = '';
					}
				}
			}else{
				self.userData = '<div class="load-fail">'+e.getMsg()+'</div>';
				if(self.getCurKey() == self.getCurKeyByEncode(opt))
					self.tipFloat.setContent();
			}			
		});
	}
	//判断取出来的数据是否为当前用户
	,checkIsSelf : function(data){
		if(!$(this.curObj).attr('rel')) return;
		var v = Util.parseKnV($(this.curObj).attr('rel'));
		var opt = {};
		if(data.id != v.u){
			opt.id = v.u;
			return opt; 
		}			
		return true;
	}
	
	,getCatheKey : function(opt){
		var key = opt.name?('name@'+ opt.name):('id@'+ opt.id);		
		this.curKey = key;
		return key;
	}
	
	,addCathe : function(key,data){
		//window.usercatche[key] = data;
		this.cathe[key] = data;
	}
	
	//显示昵称用户数据
	,showFloat : function(data){
		this.userData = data;
		if(this.tipFloat) {			
			this.tipFloat.display(1);
		}else{
			this.createBox(data);
		}
	}
	
	//用户数据过滤处理
	,filterData : function(d){
		//用户样式
		var re = {};
		re.level = d.level;
		re.profileImg = d.face_m;
		re.name = d.nickname;
		re.nameUrl = Req.mkUrl('space','ta',{id:d.id});
		re.gender = d.gender == '1' ? '男' : '女';
		re.id = d.id;
		
		//if(d.province_id){
		//	var area = cityChange.getArea(d.province_id, d.city_id);
		//	re.area = '，'+area.province+' '+area.city;
		//}
		re.location = '，'+d.location;
		
		re.fans = d.fans;
		re.fansUrl = Req.mkUrl('space','fans',{id:d.id});
		
		re.youji = d.youji;
		re.youjiUrl = Req.mkUrl('space','youji',{id:d.id});
		
		re.footmark = d.footmark;
		re.footmarkUrl = Req.mkUrl('space','footmark',{id:d.id});
		
		
		re.medals = [];
		var url = Req.mkUrl('profile','medal',{id:d.id});
		for(var i=0;i<d.medal.length;i++){
			var m = d.medal[i], info = m.info, imgUrl = getCfg('basePath')+info.s_image;
			re.medals.push('<a href="'+url+'" title="'+info.name+'"><img width="24" height="24" src="'+imgUrl+'" /></a>');
		}
		re.medals = re.medals.join('');
		if(d.id != getCfg('uid')){
			re.nome = 1;
			re.flme = d.dm ? '': 'hidden';
			re.fl = 'hidden';
			re.friendship = d.friendship;
			if(d.friendship == 0){//无关系
				re.nfled = '';
				re.type = 7;
				re.fled = 'hidden';
			}else if(d.friendship == 1){ // 我关注了Ta
				re.nfled = 'hidden';
				re.type = 7;
				re.fled = '';
			}else if(d.friendship == 2){ // 他关注了我
				re.nfled = '';
				re.fled = 'hidden';
				re.type = 7;
			}else{//互相关注
				re.nfled = 'hidden';
				re.fled = 'hidden';
				re.fl = '';
				re.type = 7;
			}
		}
		return re;
	}
	,createBox : function(data){
		var self = this;
 		this.tipFloat = Xwb.use('Tip', {
			cs:'win-card',
			contentHtml : 'Loading',
			boxOutterHtml : '<div class="arrow bg-all"></div>',
			appendTo : document.body,
			autoHide : false,
			stayHover : true,
			init : false, //是否初始化了
			isHide : true,
			destroyOnClose : false,
			contextable: false,    
 			onViewReady : function( v ){
				var thisTip = this;
				X.use('action').reg('ufls',function(e){
				    thisTip.isHide = false;					
					ui.MsgBox.anchorConfirm(e.src,getText('确定要取消关注？'), function(btnId){
						if(btnId == 'ok'){
							e.lock(1);
							var uid = e.get('u'),act = e.get('f');
							Req.unfollow(uid, '', function(re) {
								if (re.isOk()){							
									$(e.src).parent().cssDisplay(0);
									$(e.src).closest('.actions').find('#unfl').cssDisplay(1);
								} else {
									ui.MsgBox.tipWarn(re.getMsg());
								}
								thisTip.isHide = true;
								e.lock(0);
							});
						}else{
							thisTip.isHide = true;
						}
					});
				});
			}, 			
			beforeShow: function(d){
				this.init = true;
			    //在这里要处理 数据和位置
				this.setContent();	
				var cls = this.setOffset();
				this.setTipCls(cls);
				ui.Tip.prototype.beforeShow.call(this);
			},
			beforeHide : function(){			
				if(self.isOnready && self.curKey !=''){
					if(this.jq('#xweibo_loading').length == 0)
						self.addCathe(self.curKey,this.getContent());
				}
				this.isUfls	= false;			
				if(this.init) self.curObj = '';
				self.curKey = '';
				this.isHide = true;
				ui.Tip.prototype.beforeHide.call(this);
			},
			clearHideTimer : function(){
				self.clearHideTimer();
			},
			setHideTimer : function(p){
				if(this.isHide){				    
					self.setHideTimer();
				}
			},			
			setContentBefore : function(){
				var html = this.get_Content();				
				if(html){
					this.jq('.win-box').html(html);
				}
			},
			setContent : function(){
				this.setContentBefore();
			},			
			get_Content : function(){
				if( self.userData){
					if(typeof self.userData == 'object'){//处理浮层位置
						if(self.userData.sinaid)
							return T.parse(T.get('SinaUserCard'),self.userData);
						return T.parse(T.get('UserCard'),self.userData);
					}else{
						return self.userData;
					}
				}else{
					return '<div id="xweibo_loading" class="loading"></div>';
				}		
			},
			
			getContent : function(){
				return this.jq('.win-box').html();
			},
			//重新定位浮层高度
			resetPosition : function(){
				var cls = this.getView().className;
				if(Util.ie6){
					this.getView().className = '' 
					this.getView().className = cls;
				}
				if(cls.indexOf('arrow-b')>-1 || cls.indexOf('arrow-l')>-1){
				    var curA = $(self.curObj), coff = curA.offset(), height = this.jq().height();
					this.offset({top:coff.top - height});
				}
			},
			
			
			//计算显示位置
			setOffset : function(){
				var height = $(this.view).height();
				var curA = $(self.curObj), off = curA.offset(), info = this.browseInner()// 总高
				,limitTop = 220, left = 0, top = 0, cls = '';
				
				//处理@换行浮层错位问题
				var outLaw = false;
				if(off.left+350>info[0]){//左边显示	
					if(off.top - limitTop > info[2]){
						cls = 'win-pop win-card arrow-b'; 
						top = off.top - height ;						
					}else{
						cls = 'win-pop win-card arrow-r';
						top = off.top + curA.height();
					}
					left = off.left - 310;
				}else{//在上面显示
					if(off.top - limitTop > info[2]){
						cls = 'win-pop win-card arrow-l'; 						
						top = off.top - height ;	
						left = off.left;//处理@换行浮层错位问题
					}else{//在下面显示器
						cls = 'win-pop win-card';
						top = off.top + curA.height();
						left = off.left;//处理@换行浮层错位问题
					}
					left = off.left - 30;
				}
				//if(self.curObj.tagName.toUpperCase() == 'IMG'){
					left += curA.width()/2;
				//}
			    this.offset({top:top,left:left});
				return cls;
			},
			
			setTipCls : function(cls){
				this.getView().className = cls;
			},
			
			browseInner : function(){
			   var pageWidth = win.innerWidth,pageHeight = win.innerHeight;
				if (typeof pageWidth != "number"){
					pageWidth = document.documentElement.clientWidth || document.body.clientWidth;
					pageHeight = document.documentElement.clientHeight || document.body.clientHeight;
				}
				var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
				return [pageWidth, pageHeight, scrollTop];
			}
		});
		this.tipFloat.display(1); 
	} 
}));


//反馈
X.reg('feedBack',{
    view: 'feedBack',
	toggleCls: 'fb-hide',
	ftTxt: "在此处填写您的意见或建议",
	isShow: FALSE,
	init: function(){
	    var self = this;
		var $v = self.view = $( T.parse(self.view ));
		$("body").append($v);
		$v.find("#fbHandle").click( Util.bind(self.toggle,self) );
		
		self.tarCssRight = $v.css("right");
		$v.css("right", self.tarCssRight);  //写定初始值
		
		var $ta = self.$ta = $v.find("textarea");
		$ta.focusText( self.ftTxt,"focus");
		
		$v.find("#fb_submit").click(function(){
		    var v = $ta.val();
		    if( v === self.ftTxt || v.lenght > 500 ){
			    return false;
			}
			Req.feedBack({text: v}, function(e){
			    if( e.isOk() ){
		    		$v.find("div.tips").cssDisplay(1);
					self.$ta.val( '' );
					setTimeout(function(){
			    		self.toggle.call(self);
						self.clear();
					}, 2000);
			    }else MB.alert("提示", e.getError() );
			})
			return false;
		});
	},
	toggle: function(){   //折叠/收起
	    var self = this;
		var $v = self.view;
		var tarCssRight = this.isShow ? self.tarCssRight : 0; 
		if(this.isShow = !this.isShow){
		    $v.removeClass(self.toggleCls);
		}			
		$v.animate({"right": tarCssRight}, 400, function(){
			if(!self.isShow){
			    self.$ta.val( self.ftTxt );
				$v.addClass(self.toggleCls);
			}
		});
	},
	clear: function(){
	    this.view.find("div.tips").cssDisplay(0);
	}
});

//获取礼品
X.reg('giftBox',function( cfg ){
    var gb = X.use('Box', $.extend({
	    cs : 'win-fixed user-info',
		contentHtml : 'giftBox',
		appendTo : doc.body,
		destroyOnClose : TRUE,  //关闭销毁
    	closeable : TRUE,
		onViewReady : function( cfg ){
		    var self = this;
			self.jq("#submitBtn").click(function(){
			    var inps = self.jq("form input:text")
			        , parmStr = ['id='+self.jq('form input:hidden').val()]
 				    , TipText = ['姓名','电话','邮寄地址','QQ号码','Email']
					, reg = [null, /^\d{6,11}$/, null, /^[1-9]\d{4,9}$/, /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/];
				for(var i=0, len=inps.length; i<len ;i++){
				   	var v = $.trim(inps[i].value);
				   	if( !v ){
				       MB.alert("提示", TipText[i] + "不能为空", function(){ Util.focusEnd(inps[i]) } );
				       return ;
					}
					else if( reg[i] && !reg[i].test(v) ){
					   MB.alert("提示", TipText[i] + "的格式不对", function(){ Util.focusEnd(inps[i]) } );
					   return ;
					}
				    else parmStr.push( inps[i].name + '=' + v );
				}
			    Req.saveWinnerInfo( parmStr.join('&'), function( e ){
				    if(e.isOk()){
						self.allowClose = 'allow';
						self.close();
						MB.success("提示","谢谢您的参与!我们的客服会尽快联系您,奖品将寄往你的详细地址.");
					}else MB.alert("提示",e.getError())
				})
			})
		},
		close: function(){
			var self = this;
			if( this.allowClose !== 'allow' ){
				MB.confirm("提示", "您的中奖信息还没提交,真的要关闭吗?", function(r){
				    if( r === 'ok' ){
						base.close.call(self);
					}
				});
			}else base.close.call(self);
		}
	}, cfg ));
	gb.display(1);
});

//中奖邀请
X.reg('invite', function( cfg ){
    cfg = {
	   userLink: "http://dev.ziyou.com/",
	   uname: "道道111189",
	   imgSrc: "../../img/spots_group/beibao.jpg",
	   inviteSrc: X.cfg.basePath+"events/invite"
	}
	if( $("div.top-boot")[0] )
	    $("div.top-boot").replaceWith( $(T.parse('invite', cfg )) );
	else 
	    $(T.parse('invite', cfg )).insertBefore( $("#container div.main-box") ).animate({height:50},'slow')	
	
})

//游记相关模块
var Youji = mod.Youji = {};

Youji.SummaryEditer = Util.create(Base, {
    getData : function() {
        var $caption = this.$caption,
            $spots = this.$spots,
            
            titleVal = $caption.val(),
            spotsData = $spots.data('spotsData') || {},
            spotsNameInput = $spots.val() == $spots.data('defaultText') ? '': $spots.val();
            
        var data = {
            title : titleVal == $caption.data('defaultText') ? '' : titleVal,
            spots_id : spotsData.id || '',
            spots_name : spotsData.name || spotsNameInput || ''
        };
        
        return data;
    },
    
    //标题
    $caption : null,
    
    //景点搜索框
    $spots : null,
    
    onViewReady : function() {
        var $inputs = $("#youji_caption,#traceAt");
        
        this.$caption = $inputs.eq(0);
        this.$spots = $inputs.eq(1);
        
        this.$caption.focusText('', 'upload-txt-s1', this.$caption, 0, 3);
        
        //景点搜索框
        var $search_bar = this.jq('#youji_spots_search');
        if ($search_bar.length){
            var $traceAt = this.jq("#traceAt");
            X.use('search', {
                inputor : $traceAt,
				defaultText :　'',
                view : $search_bar[0],
                catchClick : true,
                catchEnter : true,
                affixfun:function(data){
                    var row,jqObj = $traceAt,val = jqObj.val();
                    for(var key in data.spots){
                        if(val == data.spots[key].name){
                            row = data.spots[key];
                            break;
                        }
                    }
                    if(row){
                        jqObj.val(row.name).data('spotsData',{
                            name :row.name,
                            id : row.id
                        });
                        return true;
                    }
                },
                onEnter : function(e, row, data, index){
                    $traceAt.val(row.name).data('spotsData',{
                        name :row.name,
                        id : row.id
                    });
                }
            });
        }
    },
    
    setSpots : function(data) {
        this.$spots.data('spotsData', data);
    }
})


//游记发表后的分享界面
/*
Youji.ShareBox = Util.create(ui.Layer, {
    view : 'youjiShare',
    appendTo : '#container',
    mask : false,
    keyEvent : false,
    onViewReady : function() {
        var basePath = X.getCfg('basePath');
        var flashvars = {
            youji_id : '',
            flashFun : 'upload',
            jsFunc :  'flashShareCallback',
            _PHPSESSID : $('#_PHPSESSID').val(),
            upload : Req.jsAPI('youjiApi','shareYouji')
        }
        
        var imgs = $.parseJSON(this.data.img_data);
        
        $.each(imgs, function(i, m) {
            flashvars[ 'img_' + i ] = encodeURIComponent(m.thumbnail_pic.url);
        });
        
        var params = {
            AllowScriptAccess:"sameDomain",
            wmode:"transparent"
        };
        swfobject.embedSWF( basePath + 'flash/imgPro.swf', 'youji_share_flash', "285", "400", "10.0.0", "expressInstall.swf", flashvars, params);
        
        window.flashShareCallback = function() {
            console.log(arguments);
        }
        
        this.loadFriendSearch();
    },
    //查询已经绑定哪些社区帐号,初始化好友搜索
    loadFriendSearch : function() {
        var self = this;
        Req.getFriendService(function(r){
            if (r.isOk()) {
                var data = r.getData(),
                    enables = data.enabled;
                
                var supports = [
                        {type : 'sina', icon : 'sina', name : '新浪微博'}, 
                        {type : 'qq' , icon : 'qq', name : '腾讯微博'}, 
                        {type : 'renren', icon : 'rr', name : '人人网'}
                    ],
                    list = [];
                
                $.each(supports, function(i, item){
                    var type = item.type;
                    item.enabled = enables[type] ? true : false;
                });
                
                self.initFriendSearch(supports);
            }
        });
    },
    
    //搜索框初始化
    initFriendSearch : function(list){
        var $search = this.jq('#friend_search');
        var listHtml = [];
        //'<a href="#"><i class="ico-sina-s2"></i>新浪微博</a>'
        var defaultIcon;
        $.each(list, function(i, item){
            if (item.enabled && !defaultIcon) defaultIcon = item.icon;
            listHtml.push('<a href="#"><i class="ico-'+item.icon+'-s2"></i>'+item.name+'</a>');
        });
        
        $search.html(T.parse('youjiShareInput', {
            icon : defaultIcon,
            droplist : listHtml.join('')
        }));
    }
});
X.reg('YoujiShare', Youji.ShareBox);
*/



/**
 * 页面内容自动加载
 **/
 X.reg('ScrollLoad', Util.create(Base, {
	scrollLock : false,
	blockOff : 50,
	curPage : 1,
	maxPage : 10,
	func : $.noop,
	ajax : Req.postReq,
	loadError : $.noop,
	loadHtml : '<div class="loading" id="scrollLoading"></div>',
	autoRender : true,
	innerViewReady : function(v){
		var self = this;
		if(this.url)
			$(win).scroll( function() { self.loadData && self.loadData.call(self);} );
	},
	
	getParam : $.noop,
	
	 //加载下一页数据
	loadData :function(exp){	
		if(!this.scrollLock && (this.compute()<=0 || exp)){ 
			//ajax请求
			this.scrollLock = true;
			this.loading(true);
			var self = this, data = {};
			if(this.hasParam){
				data = this.getParam();
			}
			this.ajax.call(Req,this.url,data,function(r){
				if(r.isOk()){
					var d = r.getData();						
					self.url = d.url;
					self.curPage ++;
					if(self.maxPage){
						if(self.curPage<self.maxPage && d.url) self.scrollLock = false;
						else self.scrollLock = true;
					}else{
						self.scrollLock = d.url == ''?true:false;
					}							
					self.scrollLoadAfter(self.orgData?r:d);					
				}else{					
					self.loadError(r);
				}				
				self.loading(FALSE);
			}, {method: 'GET'});
		}
	},
	
	//计算是否要读取数据
	compute : function(){
		var pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight; //页面高度		
		var scrollOffTop = document.documentElement.scrollTop || document.body.scrollTop; // 滚动条离顶部距离		
		var viewHeight = document.documentElement.clientHeight || document.body.clientHeight; //可视区高度		
		return pageHeight - scrollOffTop - viewHeight - this.blockOff;
	},
	
	loading : function(T){
		var dom = $('#scrollLoading');
		if(dom.length){
			dom.cssDisplay(T);
		}else{
			$(this.loadHtml).insertAfter(this.jqCt);
		}		
	},
	
	scrollLoadAfter : function(d){
	    var htmls = $.trim(d.html), htmls = $(htmls);
		if(typeof(this.jqCt) == 'string') this.jqCt = $(this.jqCt);
		htmls.appendTo(this.jqCt)
		this.cb && this.cb(d, htmls);
	}

}));

//本地存储
ui.localStorage = function(page){
	
	if (!('localStorage' in win)) {
		/**
		 * @ignore
		 */
		win.localStorage = (function() {
			var documentElement, isIE = !!document.all;
	
			if (isIE) {
				documentElement = document.documentElement;
				documentElement.addBehavior('#default#userdata');
			}
	
			return {
				setItem: function(key, value, filename) {
					if (isIE) {
						documentElement.setAttribute(key, value);
						documentElement.save(filename ? filename: key);
					}
					else {
						win.globalStorage[location.hostname][key] = value;
					}
				},
				getItem: function(key, filename) {
					if (isIE) {
						try{
							documentElement.load(filename ? filename: key);
							return documentElement.getAttribute(key);
						}catch(e){
							return '';
						}
					}
	
					return win.globalStorage[location.hostname][key] || '';
				},
				removeItem: function(key, filename) {
					if (isIE) {
						documentElement.removeAttribute(key);
						documentElement.save(filename ? filename: key);
					}
					else {
						win.globalStorage[location.hostname].removeItem(key);
					}
				}
			};
		})();
	}
	return {
		page : page,
		get : function(key, filename){
			return localStorage.getItem(key, filename);
		},
		
		set : function(key, value, filename){
			return localStorage.setItem(key, value, filename);
		},
		
		remove : function(key, filename){
			return localStorage.removeItem(key, filename);
		},
		
		initEx : function(dom){

		}
		
	}
}();

//景点点评
X.reg('PointComment', Util.create(ui.Box, {
	autoRender : true,
	actionMgr : TRUE, 
	appendTo : 'body',
	cs : 'win-tips-s2',
	type : 'haveBeen',//去过(haveBeen)或想去(wantTo)
	closeable : true,
	contentHtml : 'PointComment',
	destroyOnClose : true,
	onViewReady : function(e){
		if(this.offset){
			$(this.view).offset(this.offset);			
		}		
		this.jq('#con').focus();
	},
    onactiontrig : function(e) {
		switch(e.data.e){
			case 's' : 
				this.save(e);
			break;
		}
	},
	save : function(e){
		var text = Util.trim(this.jq('#con').val());
		if(text){
			if(Util.byteLen(text)>140){
				this.showError('分享内容不能超过140个字');
				return;
			}
			var self = this;
			e.lock(1);
			Req.pointComment(this.sid, text, '', function(er){
				e.lock(0);
				
				if(er.isOk()){
					self.close();
					MB.tipOk('分享成功');
				}else{
					self.showError(er.getMsg());
				}
			});
			
		}else{
			this.showError('请输入分享内容');			
		}
	},
	
	showError : function(msg){
		this.jq('#error').html(msg).cssDisplay(1);		
	},
	
	hideError : function(){
		this.jq('#error').cssDisplay(0);				
	}	
}));

//国省市联动
mod.Location = {
	/*  数据格式如下
		{
			1: {
				name: "中国",
				provinces: {
				  1: {
					name: "新疆",
					citys: {
					  2: "乌鲁木齐"
					  //ddd: xxxx......
					}
				  }
				}
			},
			2 : {
				name: "海外",
				provinces: {
					1: {
						name: "亚洲",
						citys: {
							1: "日本",
							//2: .....
						}
					}
				}
			}
		}
	*/	
	data: null,
	$s1: null,   	//国 or 海外  三级地域
	$s2: null,      //省 or 州
	$s3: null,	 	//市 or 国
	
    init: function( locationData, s1Selectror, s2Selectror, s3Selectror, defSetting ) {
	    this.data = locationData;
        if( !this.data )
		   return;     
        var $s1 = this.$s1 = $(s1Selectror);
		var $s2 = this.$s2 = $(s2Selectror);
		var $s3 = this.$s3 = $(s3Selectror);
		
		if(!$s1[0] || !$s1[0] || !$s3[0])
		    return ;
		
		if( !defSetting ){
			if( $s1.val() && $s2.val() && $s3.val() )
				defSetting = {s1: $s1.val(), s2: $s2.val(), s3: $s3.val() }; //默认 中国 , 北京, 海淀
			else defSetting = {s1: 1, s2: 5, s3: 1 }; //默认 中国 , 北京
		}
		var self = this;
		
		self.createCountry(defSetting.s1);
		self.createProv(defSetting.s2);
		self.createCity(defSetting.s3);
		
		if( $.browser.msie && $.browser.version == '6.0' ){   //IE6在更新select里面的option后不能立即设置其选中项
			setTimeout(function(){
				self.selectByVal( self.$s2, defSetting.s2 );
				self.createCity();
				setTimeout(function(){
					self.selectByVal( self.$s3, defSetting.s3 );
				},0);
			},0)
		}
		self.$s1.change( function() { self.createProv();  self.createCity();   }  ); //添加联动事件
		self.$s2.change( function() { self.createCity() }  ); //添加联动事件
    },
	/**
	 * sid 选中项的值
	 */
	createCountry: function( sid ){
		var ops = [];
		for(var i in this.data){
			var d = this.data[i];
			ops.push('<option value="'+i+'">'+d.name+'</option>');
		}
		this.$s1.html( ops.join('') );
		
		this.selectByVal( this.$s1, sid || 0);
	},
	createProv: function( sid ){
		var s1Val = this.$s1.val(), 
			s2data = this.data[s1Val]['provinces'],
			ops = [],
			firstOpText =  (s1Val == 1 ? '省/直辖市' : '洲');
		this.$s2.attr('vrel', this.$s2.attr('vrel').replace(/(ne=[^|]*)(?=\||$)/, function(s1){
				return s1 ? 'ne=m:<em>'+ firstOpText +'不能为空</em>' : '';
			})
		);
		ops.push('<option value="">'+ firstOpText +'</option>');
		if( s1Val ) {
			for(var key in s2data){
				ops.push('<option value="'+key+'">'+s2data[key].name+'</option>')
			}
		}
		this.$s2.html( ops.join('') );
		
		this.selectByVal( this.$s2, sid || 0);
	},
	createCity: function( sid ){
		var s1Val = this.$s1.val(), 
			s2Val = this.$s2.val(), 
			ops = [],
			firstOpText =  (s1Val == 1 ? '城市/地区' : '国家');
		this.$s3.attr('vrel', this.$s3.attr('vrel').replace(/(ne=[^|]*)(?=\||$)/, function(s1){
				return s1 ? 'ne=m:<em>'+ firstOpText +'不能为空</em>' : '';
			})
		);
	    ops.push('<option value="">'+ firstOpText +'</option>');
		
		if( s1Val && s2Val ) {
		    var pdata = this.data[s1Val]['provinces'];
			if( pdata && pdata[s2Val] && pdata[s2Val]['citys'] )
			{
				var s3data = pdata[s2Val]['citys'];
				for(var i in s3data){
					ops.push( '<option value="'+i+'">'+s3data[i]+'</option>' );
				}
			}
		}
		this.$s3.html(ops.join(''));
		
		
		this.selectByVal( this.$s3, sid || 0);
	},
	
	selectByVal: function($select, val){
		if( !val )
		    return ;
		var ops = $select.children('option') , len = ops.length;
		for(var i=0; i<len; i++){
			if( ops[i].value == val ){
				$select[0].selectedIndex = i;
				//ops[0].setAttribute('selected','selected');
				break;
			}
		}
	},
	
	getArea : function(data, country_id, province_id, city_id){
		var country = data[country_id], cName = '';
		if(country){
			var cName = country.name, prv = country['provinces'][province_id], prvName = '', cityName = '';
			if(prv){
				prvName = prv['name'];
				cityName = prv['citys'][city_id] || '';
			}
			return {countryName : cName, province : prvName, city: cityName};
		}
		return false;
	}
};

ui.JourneyInfo = X.reg('JourneyInfo', Util.create(ui.Box,{	
	hasArea : {name:'上海', id:7},
	afterSelect : '', //选择地区后触发事件
	child : false,  //独立整体
	nameTips : '输入景点关键词...',
	storyTips : '可选',
	focusCls : 'input-focus',
	onViewReady : function(){
		var $areaInpt = this.jq("#areaInpt");
		if(!this.hasArea){
			//景点搜索框			
			var $search_bar = this.jq('#searchArea'), self = this;
			if ($search_bar.length){
				X.use('search', {
					inputor : $areaInpt,
					defaultText :　this.nameTips,
					view : $search_bar[0],
					unChange : true,
					catchClick : true,
					catchEnter : true,
					affixfun:function(data){
						var row,jqObj = $areaInpt,val = jqObj.val();
						for(var key in data.spots){
							if(val == data.spots[key].name){
								row = data.spots[key];
								break;
							}
						}
						if(row){
							jqObj.val(row.name).data('spotsData',{
								name :row.name,
								id : row.id
							});
							//self.afterSelect && self.afterSelect(row);
							return true;
						}
					},
					onEnter : function(e, row, data, index){
						self.afterSelect && self.afterSelect(row);
						$areaInpt.val(row.name).data('spotsData',{
							name :row.name,
							id : row.id
						});
					}
				});	
			}			
		}else{
			var row = this.hasArea;
			if($areaInpt.length)
				$areaInpt.val(row.name).data('spotsData',{
					name :row.name,
					id : row.id
				}).attr('disabled', true);
		}
		
		if(!this.child){
			var self = this;
			this.jq('#save').click(Util.bind(this.save, this));
			this.jq('#cancel').click(function(e){
				e.preventDefault();
				self.close();
			});
		}
		
		$areaInpt.focus(function(e){
			if(Util.trim($areaInpt.val()) == self.nameTips){
				$areaInpt.val('');
			}
			$areaInpt.addClass(self.focusCls);
		}).blur(function(){
			if(Util.trim($areaInpt.val()) == ''){
				$areaInpt.val(self.nameTips);
			}
			$areaInpt.removeClass(self.focusCls);
		});
		
		var st = this.jq('#story');
		st.focus(function(e){
			if(Util.trim(st.val()) == self.storyTips){
				st.addClass(self.focusCls).val('');
			}
			st.addClass(self.focusCls);
		}).blur(function(){
			if(Util.trim(st.val()) == ''){
				st.val(self.storyTips);
			}
			st.removeClass(self.focusCls);
		});
		

		this.createTime();
	},
	
	save : function(e){
		e.preventDefault();
		var data = this.getInfo();
		if(data !== false){//保存旅程			
			console.log(data);
		}
	},
	
	createTime : function(y , n){
		var sels = this.jq('#jTime select'), years = ['<option value="">年份</option>']
		, months = ['<option value="">月份</option>'];
		var myDate = new Date(), nowYear = myDate.getFullYear(), nowMonth = myDate.getMonth();
		for(var i = nowYear; i>1970; i--){
			years.push('<option value="'+i+'">'+i+'</option>');
		}
		sels.eq(0).html(years.join(''));
	
		y = y || nowYear;
		setTimeout(function(){sels.eq(0).val(y)},1);
		for(var i = 1; i<13; i++){
			months.push('<option value="'+i+'">'+i+'</option>');
		}					
		sels.eq(1).html(months.join(''));
		if(n) sels.eq(1).val(n);
	},
	
	getInfo : function(){
		var inpt = this.jq("#areaInpt"), area = {};
		if(inpt.length){
			var _area = inpt.data('spotsData'), v = $.trim(inpt.val());
			if(v == '' || v == this.nameTips){
			//if(!area){
				this.showTips('请填写旅行地点', '', inpt);
				//inpt.focus();
				return false;
			}else{
				if(_area && _area.id){
					area.id = _area.name == v?_area.id:''
				}else
					area.id = '';
				area.name = v;
			}
		}else{
			area = this.hasArea;
		}
		
		var sels = this.jq('#jTime select'), year = sels.eq(0).val(), month = sels.eq(1).val();
		if(month && !year){
			this.showTips('请选择年份');
			return false;			
		}
		
		var story = Util.trim(this.jq("#story").val());
		story = story == this.storyTips?'':story;
		if(Util.byteLen(story)>80){
			this.showTips('旅行故事描述不能超过80个字符，40个汉字。', '', this.jq("#story"));
			return false;	
		}
		return {area: area, time : [year, month], story:story};
	},
	
	reset : function(data){
		this.jq("#areaInpt").data('spotsData', data?data.area:'').val(data?data.area.name:this.nameTips);
		var sels = this.jq('#jTime select');
		var myDate = new Date(), nowYear = myDate.getFullYear()
		sels.eq(0).val(data?data.year:nowYear);
		sels.eq(1).val(data?data.month:'');
		this.jq("#story").val(data?data.story:this.storyTips);
	},
	
	showTips : function(msg, obj, focusObj){
		obj = obj ? obj : this.jq('#tips');
		if(obj.length == 0)
			X.use('msgbox').alert('',msg, function(){
				focusObj && focusObj.focus();
			})
		else{			
			obj.text(msg).cssDisplay(1);	
			focusObj && focusObj.focus();
		}
	}
}));



//选择旅途图片
ui.SelectJourneyPic = X.reg('SelectJourneyPic', Util.create(ui.Box,{
		
        contentHtml : 'SelectJourneyPic',
        
        autoRender : TRUE,		
		
		actionMgr:true,
		
		youji : Req.mkUrl('youji','create'),		
		
		typeChange : true,
		
		cache : {},
		
		close : function(){
			X.ui.Box.prototype.close.call(this);
			this.closeBefore && this.closeBefore();
		},
		
		onactiontrig:function(e){
			switch(e.data.e){
				case 'save':
					var lis = this.jq('#imgList li.selected'), pics = [];
					for(var i=0, len = lis.length;i<len;i++){
						var o = Util.parseKnV(lis.eq(i).attr('rel'));
						pics.push({id:o.i,postcard_id:(o.t?'p':''),img_data :{small_pic:lis.eq(i).find('img').attr('src')}});
					}
					this.saveAfter && this.saveAfter(this.selects);
					this.close();
				break;
				
				case 'cancel':						
					this.close();
				break;
				
				case 'sc': //切换tab
					var type = e.get('i'), p = '', lp = this.jq('#labelPart'), childs = lp.children();
					if(type == 0){
						p = childs.eq(childs.length>1?1:0);
					}else{
						p = childs.eq(0);
					}
					var $e = p.children().eq(0);
					//if(p.hasClass('cur')){
					//	this.typeChange = false;
					//}else{
						var lied = lp.find('.cur'), span = lied.find('span'), rel = span.attr('rel');
						lied.removeClass('cur');
						span.replaceWith('<a href="#" rel='+rel+'>'+span.text()+'</a>');
						p.addClass('cur');
						$e.replaceWith('<span  rel='+$e.attr("rel")+'>'+$e.text()+'</span>');
						this.typeChange = true;
					//}
					this.getPage(1, type);
				break;
				
				case 'sel'://选择图片
					var id = e.get('i'), $e = $(e.src), p = $e.parent(), ched = p.hasClass('selected');
					if(ched){
						p.removeClass('selected');
						this.delSelected(e.get('t'), id);
					}else{
						if(this.addSelect(e.get('t'), id, $e.find('img').attr('src'))){
							p.addClass('selected');
						}
					}
					
					this.setSelectCount();
				break;
			}	
		},
		
		reset : function(){
			this.cache = {};
			this.jq('#labelPart>li').eq(0).find('a').click();
		},
		
		saveAfter : function(d){
			var imgs = [], pimgs = [], self = this;
			for(var i=0,len=d.length;i<len;i++){
				if(d[i].t == 'i') imgs.push(d[i].id)
				else pimgs.push(d[i].id);
			}
			var ed = this.editData, year = '', month = '', ym = ed.journey_time;
			var jt = ym == '0'?'':ym*1000;
			if(jt){
				jt = new Date(jt);
				year = jt.getFullYear();
				month = jt.getMonth()+1;
			}
			Req.journeyUpdate(ed.id, 1, year, month, ed.content, imgs.join(','), pimgs.join(','), ed.spot_id, ed.spot_name, function(r){
				if(r.isOk()){
					if(self.callBack) self.callBack(r.getData());
				}else{
					
				}
			});
		},
		
		getPage : function(page, type, fn){
			var self = this, sid, cacheKey, name;
			this.type = type || this.type;
			if(type == 1){
				sid = this.area && this.area.id;
				name = this.area && this.area.name;
				cacheKey = sid+'_'+page;
			}else{
				sid = '';
				cacheKey = 'all_'+page;
			}
			var curData = this.cache[cacheKey];
			if(curData){
				this.createImgs(curData.list, type);
				if(this.typeChange) this.createPage({total:curData.total_number,type:type});
				fn && fn();
				this.typeChange = false;
			}else
				Req.journeyPhoto(page, sid, name, '', function(e){
					if(e.isOk()){
						var d = e.getData();				
						self.createImgs.call(self, d.list, type);				
						if(self.typeChange) 
							self.createPage({total:d.total_number,type:type});
						self.typeChange = false;
						self.cache[cacheKey] = d;
						fn && fn();
					}
				})
		},
		
		setShowPart : function(len, type){
			var all = this.jq('#allNoImg'), spots = this.jq('#spotsNoImg'), noImgFoot = this.jq('div.travels-desc');
			if(len > 0){
				all.cssDisplay(0);
				spots.cssDisplay(0);
				noImgFoot.cssDisplay(0);
			}else{
				if(type == 0){
					spots.cssDisplay(0);
					all.cssDisplay(1);
				}else{
					all.cssDisplay(0);
					spots.cssDisplay(1);
				}
				noImgFoot.cssDisplay(1);
			}
		},		
		
		createImgs : function(data, type){
			var imgs = [], len = data.length;
			for(var i=0;i<len;i++){
				var d = data[i], pid = d.postcard_id||"", obj = d.url?d:{id:d.postcard_id || d.id, url:this.getShowImage(d.img_data), pid:pid};
				var id = pid?d.id||d.postcard_id:d.img_id;
				var cls = this.isSelected(pid, id)?'selected':'';
				imgs.push('<li rel="i:'+id+',t:'+pid+'" class="'+cls+'"><a href="#" rel="e:sel"><img src="'+obj.url+'" alt="" /><i></i></a></li>');
			}
			this.jq('#imgList').html(imgs.join(''));
			this.setShowPart(len, type);
			this.setSize();
		},		
		
		setSize : function(){
			var imgs = this.jq('#imgList img'), len = imgs.length;
			for(var i=0;i<len;i++){
				Util.getImageSizeByValue(imgs[i], 80);
			}			
		},
		
		getShowImage : function(imgObj){
			if(imgObj.small_pic)
				return imgObj.small_pic.url;
			else if(imgObj.thumbnail_pic) return imgObj.thumbnail_pic.url;
			else return imgObj.web_pic.url;
		},
		
		setSelectCount : function(){
			this.jq('#selectCount').text(this.selects.length);
		},
		
		isSelected : function(pid, id){
			var pid = pid?'p':'i';
			for(var i=0, sts = this.selects, len = sts.length;i<len;i++){
				if(pid == sts[i].t && sts[i].id == id){
					return true;
				}
			}
			return false;
		},
		
		delSelected : function(pid, id){
			var pid = pid?'p':'i';
			for(var i=0, sts = this.selects, len = sts.length;i<len;i++){
				if(pid == sts[i].t && sts[i].id == id){
					sts.splice(i, 1);
					return true;
				}
			}
			return false;
		},
		
		addSelect : function(pid, id, url){
			var sts = this.selects, len = sts.length, pid = pid?'p':'i';
			if(len >= 5 ){
				MB.alert('', '选择的图片不能超过5张');
				return false;
			}else{
				this.selects.push({id: id, t:pid, url:url});
				return true;
			}
		},
		
		onViewReady : function(){
			this.jq('#createYouji').attr('href',this.youjiSpotUrl);
			this.getPage(1, this.area?1:0);
		},
		
		createPage : function(d){			
			var _this = this, pageArea = this.jq('#pageArea'), pageSize = 20;
			if(d.total/pageSize <= 1){
				pageArea.parent().cssDisplay(0);
				return;
			}
			pageArea.html('');
			X.use('Page',{
				total : d.total,
				pageSize : pageSize,
				type : d.type,
				view : '<span></span>',
				pageModel : function(big, leftLine, rightLine){
					var pageHtml = [], first = true;
					if(this.curPage == 1){//上一页		
					}else{
						if(this.begin != 1) pageHtml.push('<a href="#" rel="e:t,na:1,n:1">1</a>');
					}
					for(var i = this.begin; i<=big; i++){
						if(first && leftLine) pageHtml.push('<span>...</span>'); 
						first = false		
						if(i == this.curPage) pageHtml.push('<span class="nullCur">'+i+'</span>');
						else pageHtml.push('<a href="#" rel="e:t,na:1,n:'+i+'">'+i+'</a>');									
					}
					
					if(rightLine){//下一页
						pageHtml.push('<span>...</span>');				
					}
					
					if(this.totalPage == this.curPage){	
					}else{
						if(big != this.totalPage)pageHtml.push('<a href="#" rel="e:t,na:1,n:'+this.totalPage+'">'+this.totalPage+'</a>');	
					}						
					this.jq().html(pageHtml.join(''));
				},
				curPage : 1,
				appendTo : pageArea,				
				loadData : function(page, fn){
					_this.getPage.call(_this, page, this.type, fn);
				}	
			});	
			pageArea.parent().cssDisplay(1);
		}	
	}
));

//添加图片
ui.JourneyImage = X.reg('JourneyImage', function(opt){
	
	    var inst = X.use('Box', $.extend({
		
        contentHtml : 'JourneyImage',
        
        autoRender : true,		

		cs : 'win-choose-pic win-fixed',
        
        mask : TRUE,
        
        closeable: TRUE,
		
		destroyOnClose : TRUE,
        
        appendTo : 'body',		
        
        //是否启用新浪相册
        sinaAlbum : true,
		
		close : function(){
			X.ui.Box.prototype.close.call(this);
			this.closeBefore && this.closeBefore();
		},		
        
		
		saveAfter : function(d){
			var imgs = [], pimgs = [], self = this;
			for(var i=0,len=d.length;i<len;i++){
				if(d[i].t == 'i') imgs.push(d[i].id)
				else pimgs.push(d[i].id);
			}
			var ed = this.editData, year = '', month = '', ym = ed.journey_time;
			var jt = ym == '0'?'':ym*1000;
			if(jt){
				jt = new Date(jt);
				year = jt.getFullYear();
				month = jt.getMonth()+1;
			}
			Req.journeyUpdate(ed.id, 1, year, month, ed.content, imgs.join(','), pimgs.join(','), ed.spot_id, ed.spot_name, function(r){
				if(r.isOk()){
					if(self.callBack) self.callBack(r.getData());
				}else{
					
				}
			});
		},
				
		onViewReady : function(){
			var self = this, bindSina = getCfg('bindSina');
			if(!bindSina){
				Req.getAlbumsService( function(r){					
					if( r.isOk() ){
						bindSina = r.getData().enabled;
						if(bindSina['sina']){
							self.jq('#tab>a:eq(2)').cssDisplay(1);		
							X.cfg.bindSina = bindSina;
						}
					}
				});
			}else{
				if(bindSina['sina']){
					self.jq('#tab>a:eq(2)').cssDisplay(1);		
				}
			}
			
			var sa = this.jq('#tab>a'), journeySelectPic = this.jq('#journeySelectPic'), flashBox = this.jq('#flashBox'), journeySinaImage = this.jq('#journeySinaImage');
			this.sw = X.use('Switcher', {
				items : sa,
				contents : [journeySelectPic, flashBox, journeySinaImage],
				selectedCS : 'cur',
				onselect : function(dom){
					var $dom = $(dom), rel = $dom.attr('rel');
					switch(rel){
						case '1' : 
							if(!self.selectImage)
								self.initSelect.call(self);
							else
								self.selectImage.setSelectCount();
						break;
						case '2' : 
							if(!self.flashUpload)
								self.initFlash.call(self);
						break;
						case '3' : 
							if(!self.selectSinaImage)
								self.initAlbums.call(self);
							else
								self.selectSinaImage.setSelectCount();
						break;
					}
				}
			});
			//this.tab = 1;
			if(this.tab){				
				if(this.tab == 1){
					this.initFlash();
				}else{
					this.initAlbums();
				}
				this.sw.select(sa.eq(this.tab)[0]);
			}else{
				this.initSelect();
			};
		},
		//选择相片
		initSelect : function(){
			var journeySelectPic = this.jq('#journeySelectPic'), self = this;			
			var youjiSpotUrl = Req.mkUrl('youji','create');
			if(opt.area){
				if(opt.area.id){
					youjiSpotUrl = Req.mkUrl('youji','create', {spots_id:opt.area.id});
				}else if(opt.area.name){
					youjiSpotUrl = Req.mkUrl('youji','create', {spots_name:opt.area.name});
				}
			}
			this.selectImage = X.use('SelectJourneyPic', {
				area : (this.area && this.area.name)?this.area : ''
				, areaName : this.area.name
				, view : journeySelectPic[0]
				, selects : this.selects
				, youjiSpotUrl : youjiSpotUrl
				, scope : this
				, num : this.selects.length
				, closeBefore : function(){
					self.close();
				}
				, saveAfter : Util.bind(this.saveAfter, this)
			}).display(1);	

			this.jq('#uploadImg,#uploadImg2,#uploadImg3').click(function(e){
				e.preventDefault();
				self.sw.select(self.jq('#tab>a').eq(1)[0]);
			})			
		},
		//上传
		initFlash : function(){
			this.succCount = 0;
			var flash = X.ui.getFlash({
					src: X.request.basePath + 'flash/multiUpload.swf?v=' + X.getCfg('subver'),
					width: 614,
					height: 400,
					id:'Xwb_MultiUpload',
					name:'Xwb_MultiUpload',
					quality: 'high',
					w3c : 1,
					allowFullscreen: 'true',
					flashvars: 'max_num=5&type=journey&jsFunc=flashCallback&upload_url='+escape('http://'+location.host+Req.jsAPI('journeyApi','uploadPic'))+'&max_size=' + (10*1024*1024),
					AllowScriptAccess:"sameDomain",
					wmode: 'opaque'
				});
				var area = (this.area && this.area.name)?this.area : '', sid = '', self = this;
				
				if(area){
					sid = this.area.id;
				}
				window.flashCallback = function(type,data){
					 if(__debug) console.log('type:'+type,'-----------data:'+data);
					switch(type){
						case 'ablum_id' :
							return '';
							break;
						case 'spot_id':
							return sid;
							break;
						case 'spot_name':
							return area.name;
							break;
						case 'allsuccessurl' :
							self.successCallback(self, data);
							break;
						case 'successurl' :
							self.onSuccess.call(self, data); 
							break;
						case 'close' :
							self.close();
							break;
					}
				}
				
				this.jq('#flashBox').html( flash );
				
				this.flashUpload = true;
		},
		
		initAlbums : function(){
			var self = this;
			var journeySinaImage = this.jq('#journeySinaImage');
			this.selectSinaImage = X.use('JourneySinaImage', {
				view : journeySinaImage[0]
				, selects : this.selects
				, closeBefore : function(){
					self.close();
					//self.closeBefore();
				}
				, saveAfter : Util.bind(this.saveAfter, this)
			}).display(1);	
		},
		
		allErrCount : 0, //上传失败数
		succCount : 0, //上传成功数
		
		collectionErr: function( ec ){
			if( ec ){
				this.allErrCount++;
			}
		},
		
		onSuccess : function(data){
			var r = new Req.DefaultResponseDefinition( $.parseJSON(data) );
			//判断数据是否正确
			if( r.isOk() ){   
				var flashRst = r.raw.rst[0]; // 这里flashRst的数据也可能会出错				
				if( flashRst && !flashRst.err ){
					this.createItem(flashRst);
					this.succCount++;
				}else	
					this.collectionErr( r.getCode() );
			}
			else 	
				this.collectionErr( r.getCode() );			
		},
		
		items : [],//上传照片缓存
		createItem : function(data){
			if(this.items.length == 5){
				this.items.splice(0, 1);
			}
			this.items.push({id:data.id, t:'i', url:this.getShowImage(data)});
		},
		
		//合并上传后数据
		mergeData : function(){
			if(this.oldData){
				var nlen = this.items.length, olen = this.oldData.length, aLen = nlen+olen ;
				if(olen == 0) return this.items;
				for(var i=aLen,j=0;i>5;i--){
					this.oldData.splice(j, 1);
					j++;
				}
				for(var i=0,olen = this.oldData.length;i<olen;i++){
					this.items.push(this.oldData[i]);
				};
			}
			return this.items;
		},
		
		getShowImage : function(imgObj){
			if(imgObj.small_pic)
				return imgObj.small_pic.url;
			else if(imgObj.thumbnail_pic) return imgObj.thumbnail_pic.url;
			else return imgObj.web_pic.url;
		},
		
		clearFlashData : function(){			
			this.succCount = 0;									
			this.allErrCount = 0;
		},
		
		successCallback : function(data){
			var self = this;
			var	btns =  [{title:'重新上传',id:'cancel', cs: 'btn-s1'},{title:'确定插入',id:'ok', cs: 'btn-s1'}];

			var htmlTips = [];
			if( self.succCount>0 || ( self.succCount == 0 && self.allErrCount == 0 ) )
				htmlTips.push('成功上传'+self.succCount+'张照片。');
			
			if( self.allErrCount>0 ){
				htmlTips.push( self.allErrCount+'张照片上传失败，请重新上传。');
			}
			X.use('Dlg',{
				appendTo: document.body,
				title:'提示',
				dlgContentHtml : 'MsgDlgContent',
				defBtn:'ok',
				mask : true,
				hasErr: self.allErrCount,
				imgData: self.uploadedImgData,
				buttons: btns,
				onbuttonclick:function(id){
					if(id == 'ok'){
						this.close();
						self.saveAfter(self.mergeData.call(self));
						self.close();
						self.selectImage && self.selectImage.reset();
						//self.sw.select(self.jq('#tab>a').eq(0)[0]);
					}else if(id == 'cancel'){
						self.selectImage && self.selectImage.reset();
						this.close();
					}
				},
				onViewReady:function(){
					this.jq('#xwb_msgdlg_ct').html(  htmlTips.join('<br/>') );
					if( !this.hasErr )
						this.jq('#xwb_msgdlg_icon')[0].className = 'icon-success';
				}
			}).display(1);
			this.clearFlashData();   //清空该次上传图片返回的所有 成功/错误信息 的数据
		}
		
	}, opt));
		
	return inst; 
});

//第三方相册
ui.JourneySinaImage = X.reg('JourneySinaImage', Util.create(Base,{	
	actionMgr:true,
	curId : '',
	onactiontrig:function(e){
        switch(e.data.e){
			case 'sel'://选择图片
				var id = e.get('i'), $e = $(e.src), p = $e.parent(), ched = p.hasClass('selected');
				if(ched){
					p.removeClass('selected');
					this.delSelected(e.get('t'), id);
				}else{
					if(this.addSelect(e.get('t'), id, $e.find('img').attr('src'))){
						p.addClass('selected');
					}
				}
				
				this.setSelectCount();
				
			break;
			
			case 'save':
				var lis = this.jq('#imgList li.selected'), pics = [];
				for(var i=0, len = lis.length;i<len;i++){
					var o = Util.parseKnV(lis.eq(i).attr('rel'));
					pics.push({id:o.i,postcard_id:(o.t?'p':''),img_data :{small_pic:lis.eq(i).find('img').attr('src')}});
				}
				this.saveAfter && this.saveAfter(this.selects);
				this.close();
			break;
			
			case 'cancel':					
				this.close();
			break;
		}
	},
	
	close : function(){
		this.selects = [];
		Base.prototype.close.call(this);
		this.closeBefore && this.closeBefore();
	},
	
	setSelectCount : function(){
		this.jq('#selectCount').text(this.selects.length);
	},
	
	delSelected : function(pid, id){
		var pid = pid?'p':'i';
		for(var i=0, sts = this.selects, len = sts.length;i<len;i++){
			if(pid == sts[i].t && sts[i].id == id){
				sts.splice(i, 1);
				return true;
			}
		}
		return false;
	},
	
	addSelect : function(pid, id, url){
		var sts = this.selects, len = sts.length, pid = pid?'p':'i';
		if(len >= 5 ){
			MB.alert('', '选择的图片不能超过5张');
			return false;
		}else{
			this.selects.push({id: id, t:pid, url:url});
			return true;
		}
	},
	
	loadLock : false,
	page : 1,
	
	onViewReady : function(){
		var self = this;
		Req.getAlbums( 'sina', getCfg('uid'), function( r ){
			if( r.isOk() ){
				var data = r.getData();
				if( data.length <= 0 ){
					self.jq('div.hd').html('相册列表为空');
					return ;
				}
						
				var html = [];
				for(var i=0; i<data.length; i++)
					html.push('<option value="'+data[i].album_id+'">'+data[i].caption+'</option>');	
					
				self.jq('select').html( html.join('') );
				
				self.jq('select').change(function(){
					self.page = 1;
					self.curId = this.value;
					self.typeChange = true;
					self.getPage.call(self, this.value, 1);
				});				
				self.getPage.call(self, data[0].album_id, 1, function(){
					self.jq('div.sina-pic').scrollTop(0);
				});
				
				self.jq('div.sina-pic').scroll(function(){
					if(!self.loadLock && ($(this).scrollTop() + $(this).height() + 40 > this.scrollHeight)){
						self.getPage(self.jq('select').val(), ++self.page);
					}
				});
	
			}
		});
		
		this.jq('#imgList').scrollTop(0);

		
		this.setSelectCount();
	},
	selects : [],
	typeChange : false,
	cache : {},
	getPage : function(id, page, fn){
		if(!id) return;
		var self = this;
		this.loadLock = true;
		var loading = this.jq('#imgList').parent().find('#loading');
		if(loading.length) loading.cssDisplay(1);
		else loading = $('<div class="loading" id="loading"></div>').appendTo(this.jq('#imgList').parent());
		this.jq('div.no-data').cssDisplay(0);
		Req.getPhotosListPage(page, 20,  'sina', id, function(r){
			loading.cssDisplay(0);			
			if(r.isOk()){
				var html="",data = r.getData();
				self.createImgs.call(self, data);
			} else {
				Box.alert('提示',r.getMsg());
			}
			fn && fn();
		});		
	},
	
	createImgs : function(data, type){
		var imgs = [], len = data.length;
		for(var i=0;i<len;i++){
			var d = data[i], pid = '', obj = {id:d.jp_id, url:this.getShowImage(d), pid:pid};
			var id = d.jp_id;
			var cls = this.isSelected(pid, id)?'selected':'';
			imgs.push('<li rel="i:'+id+',t:'+pid+'" class="'+cls+'"><a href="#" rel="e:sel"><img src="'+obj.url+'" alt="" /><i></i></a></li>');
		}
		if(this.typeChange){
			if(len){				
				this.jq('#imgList').html(imgs.join('')).cssDisplay(1);				
			}
			else{
				this.jq('#imgList').cssDisplay(0);
				this.jq('div.no-data').cssDisplay(1);
			}
			this.typeChange = false;
		}else{
			this.jq('#imgList').append(imgs.join(''));
		}
		if(len) this.loadLock = false;
		//this.setShowPart(len, type);
		this.setSize();
	},
	
	setSize : function(){
		var imgs = this.jq('#imgList img'), len = imgs.length;
		for(var i=0,len = imgs.length;i<len;i++){
			Util.getImageSizeByValue(imgs[i], 80);
		}
	},
	
	isSelected : function(pid, id){
		var pid = pid?'p':'i';
		for(var i=0, sts = this.selects, len = sts.length;i<len;i++){
			if(pid == sts[i].t && sts[i].id == id){
				return true;
			}
		}
		return false;
	},
	
	getShowImage : function(imgObj){
		return imgObj.small_pic || imgObj.thumbnail_pic || imgObj.web_pic
	}		
	
}));

//添加旅途
ui.AddJourney = X.reg('AddJourney', Util.create(Base,{	
	view : '',	
    actionMgr:true,
	pageSize : 6,
	nowArea : '',
	imgCache : {},	
	onactiontrig:function(e){
        switch(e.data.e){
			case 's' :
				this.save(e);
			break;
			case 'p' :			
				var p = $(e.src).parent().attr('p');
				this.toPage(p);
			break;
			case 'del' :
				this.delImg(e);
			break;
			case 'c' :
				this.cancel(e);
			break;		
			case 'si': //选择图片box
				var ipt = this.jq("#areaInpt");
				var area = ipt.data('spotsData'), v = $.trim(ipt.val());
				if(!area.name){
					area = {name : v == this.jinfo.nameTips ? '':v, id : ''};
					area.name = Util.escapeHtml(area.name);
				}else{
					if(area.name != v){
						area = {name : v == this.jinfo.nameTips ? '':v, id : ''};
					}
				}
				this.selectPicBox(e, area, e.get('tab'));
			break;
		}
	},
	
	autoSearchLock : false, //编辑有图片时不自动加载图片
	
	initData : function(data){ //编辑状态初始化数据
		this.status = 'edit';
		this.editId = data.id;
		this.editData = data;
		var jt = data.journey_time == '0'?'':data.journey_time*1000;
		var year = '', month = '';
		if(jt){
			jt = new Date(jt);
			year = jt.getFullYear();
			month = jt.getMonth()+1;
		}		
		this.jinfo.reset({year:year, month:month||'', area:{name:data.spot_name, id:data.spot_id}, story:data.content});		
		if(data.type == '1'){//当type为0是表示图片不是用户本身的
			this.createImgs(data.img);					
			data.img.length && (this.autoSearchLock = true)
		}
			
	},
	
	save : function(e){
		var data = this.jinfo.getInfo(), self = this, pics = this.getSavePicInfo();		
		if(data){
			e.lock(1);
			function suc(r){
				e.lock(0);
				if(r.isOk()){
					self.journeyInsert ? self.journeyInsert(r.getData(), self.status) : MB.success('', '成功') ;					
				}else{				
					MB.alert('', r.getMsg());
				}
			}
			
			if(this.status == 'add')
				Req.addJourney(data.time[0], data.time[1], data.story, pics[1], pics[0], data.area.id, 1, data.area.name, 0, function(r){
					suc(r);
				});
			else {
				Req.journeyUpdate(this.editId, 1, data.time[0], data.time[1], data.story, pics[1].length?pics[1]:'no_img', pics[0], data.area.id, data.area.name, function(r){
					suc(r);
				});
			}
		}
	},
	
	cancel : function(){
		this.closeLayer && this.closeLayer(0);
		this.setRightArea('noPic');
		this.reset();
		//this.jinfo.reset();		
	},
	
	reset : function(){
		this.jinfo.reset();
		//this.setRightArea('noPic');	
		this.jq('#tips').cssDisplay(0);		
	},
	
	//图片列表功能	
	getImgByArea : function(data, page){
		var self = this;
		if(this.imgCache[data.id]){
			this.createImgs(this.imgCache[data.id], page, 1);
			return;
		}
		this.setRightArea('load');
		Req.journeyPhoto(page, data.id,'', '' , function(e){
			if(e.isOk()){
				var d = e.getData();
				self.imgCache[data.id] = d.list;			
				self.createImgs(d.list, page, 1);
			}
		})
		
	},
	
	toPage : function(p){
		if(this.nowArea)
			this.getImgByArea(this.nowArea, page);
	},
	
	delImg : function(e){
		var li = $(e.src).closest('li'), p = li.parent();
		li.remove();
		if(p.find('li').length == 0){
			this.setRightArea('noPic');
		}
		this.jq('#snum').text(p.find('li').length);		
	},
	
	getSelectPic : function(){
		var lis = this.jq('#jPic ul.list li'), pics = [];
		if(!this.jq('#jPic div.chosen').hasClass('hidden')){
			for(var i=0, len = lis.length;i<len;i++){
				var o = Util.parseKnV(lis.eq(i).attr('rel'));
				pics.push({id:o.i, t:(o.t?'p':'i'), url:lis.eq(i).find('img').attr('src')});
			}
		}
		return pics;
	},
	
	getSavePicInfo : function(){		
		var pics = this.getSelectPic(), postcard_id = [], img = [];
		if(!this.jq('#jPic div.chosen').hasClass('hidden'))
			for(var i=0, len = pics.length;i<len;i++){
				if(pics[i].t == 'p') postcard_id.push(pics[i].id);
				else img.push(pics[i].id);
			}
		
		return [postcard_id.join(','), img.join(',')];
	},
	
	getImgHtml : function(d){
		if(d.url){
			var obj = {id:d.postcard_id || d.img_id || d.id, url:d.url, pid:(d.t=='p' || d.postcard_id)?'p':''};
		}else{
			var pid = d.postcard_id||"";	
			var url = this.getShowImage(d);
			var obj = {id:d.img_id || d.id || d.jp_id, url:url, pid:pid};
		}
		return '<li rel="i:'+obj.id+',t:'+obj.pid+'"><div class="pic"><img width=50 height=50 src="'+obj.url+'" /><a href="#" title="删除" rel="e:del">删除</a></div></li>';
	},
	
	getShowImage : function(imgObj){
		if(imgObj.img_data){
			imgObj = imgObj.img_data;
		}
		if(imgObj.small_pic)
			return imgObj.small_pic.url;
		else if(imgObj.thumbnail_pic) imgObj.thumbnail_pic.url;
		else imgObj.web_pic.url;
	},
	
	setSize : function(imgs){
		for(var i=0,len = imgs.length;i<len;i++){
			Util.getImageSizeByValue(imgs[i], 50);
		}
	},
	
	
	imgHover : function(lis){
		$.each(lis,function(i,u){
			var $t = $(this)
			$t.hover(function(){
				$t.addClass('hover');
			}, function(){$t.removeClass('hover');})
		})
	},
	
	setRightArea : function(param){
		var jPic = this.jq('#jPic'), choose = jPic.find('.choose')
		, load = jPic.find('.load'), chosen = jPic.find('.chosen')
		, picNum = this.jq('#snum').parent();
		if(param == 'noPic'){
			load.cssDisplay(0);
			chosen.cssDisplay(0);
			chosen.find('ul.list').html('');
			picNum.cssDisplay(0);
			choose.cssDisplay(1);
		}
		if(param == 'load'){						
			chosen.cssDisplay(0);
			choose.cssDisplay(0);
			load.cssDisplay(1);
		}
		if(param == 'hasPic'){			
			choose.cssDisplay(0);
			load.cssDisplay(0);
			chosen.cssDisplay(1);
			picNum.cssDisplay(1);
		}
	},
	
	
	createImgs : function(re){	
		this.parentUI.display(1);
		var len = re.length, len = len>5?5:len, imgs = [];
		if(len){
			for(var i=0;i<len;i++){
				imgs.push(this.getImgHtml(re[i], 'selected'));			
			};
			this.jq('#jPic').find('ul.list').html(imgs.join(''));
			this.setSize(this.jq('#jPic').find('ul.list img'));
			this.imgHover(this.jq('#jPic').find('ul.list>li'));
			this.setRightArea('hasPic');
		}else{
			this.setRightArea('noPic');
		}
		
		this.jq('#snum').text(len);
	},
	
	cloneData : function(o){
		var n = [];
		for(var i=0, len = o.length;i<len;i++){
			n.push(o[i]);
		}
		return n;
	},
	
	
	selectPicBox : function(e, area, tab){
		var selects = this.getSelectPic(), self = this;
		this.isAutoSearch = (area && area.name) ? false : true;
		this.parentUI.display(0);
		this.parentUI._hidden = true;
		if(!this.selPicBox){
			X.use('JourneyImage', {
				area : (area && area.name)?area : ''
				, areaName : Util.escapeHtml(area.name)
				, selects : selects
				, oldData : this.cloneData(selects)
				, num : selects.length
				, tab : tab
				, closeBefore : function(){
					self.parentUI.display(1);
				}
				, scope : this
				, saveAfter : Util.bind(this.createImgs, this)
			}).display(1);				
		}		
	},
	
	isAutoSearch : false,  //是否自动加载图片
	
	afterSelect : function(data){		
		this.nowArea = data;
		if(!this.isAutoSearch && !this.autoSearchLock)
			this.getImgByArea(data, 1);
	},
	
	onViewReady : function(){
		var self = this;
		this.jinfo = X.use('JourneyInfo', {
				showTips : function(msg, obj, focusObj){
					obj = obj ? obj : self.jq('#tips');
					obj.text(msg).cssDisplay(1);
					focusObj && focusObj.focus();					
				},
				afterSelect : function(data){
					self.afterSelect.call(self, data);					
				},
				hasArea : false,
				view : $(this.view).find('#journeyInfo')[0]
		}).display(1);	
	}
	
}));	




//难忘旅途, 该控件只由 manageTrip 调用, 不单独使用
X.reg('indelibleTrip', function( cfg ){
	var inst = {
		jqView : null,
		spotApiUrl : Req.jsAPI('center','guide_spots'),
		init: function(){
			//难忘旅途选中交互
			var self = this;
			if( !this.jqView ) 
				return ;
			
			this.jqView.delegate(':checkbox','click',function(){
				var $me = $(this), $p =  $me.parent('label');
				if( $me.data('lock') == 1 )
					return false;
				$me.data('lock',1);
				function cbfunc( spotData ){
					$me.data('lock',0);
				}
				var id = this.id.replace(/^[a-zA-z]+/,'');
				var spotData = {id : id, name: self.jqView.find( '#'+ this.id +':checkbox' ).parent().text()},	
					action = $p.hasClass('selected') ? 'del' : 'add';
				self.reqSetSpot( action, spotData, cbfunc );
				return false;
			});
			self.resetContent();
			
			X.use('action')
			.reg('cc', Util.bind( self.resetContent, self ) )
			.reg('delSpot', function(e){  //添加难忘旅途
				self.reqSetSpot( 'del', { id: e.data.id } );
			})
		},
		
		lockReq : false,
		
		resetContent : function(e){
			var self = this;
			if( self.lockReq || !self.spotApiUrl )
				return ;
			self.lockReq = true;
			Req.postReq( self.spotApiUrl, '', function(rst){
				if(rst.isOk()){
					var data = rst.getData();
					var spots = data.spots, html = [];
					for(var k in spots)
						html.push( T.parse('spotsItem2', spots[k] ) );
					if( html.length ){
						html.push(T.parse('spotsItem2Last'));
						self.jqView.find('ul.triplist').html( html.join('') );
						self.setSearchBox();  //重置搜索框
					}else  self.jqView.find('ul.triplist').html( '没有可添加的景点了!' );
					
					self.spotApiUrl = data.url;
					if( !data.url ){
						self.showChangeBtn( 0 );
						return ;
					}
					self.showChangeBtn(1);
				}
				self.lockReq = false;
			}, {});
		},
		
		spotid_prefix : 't',   //景点id带的前缀
		/** 请求删除难忘旅途
		 *	@param {string} action  等于 'add' or 'del' ,删除或者添加难忘景点
		 * 	@param {Object} spotData {id: xxx, name: 'xxx'}
		 *	@param {function} cbfunc 操作成功后,自定的回调,可为空
		 */
		reqSetSpot : function( action, spotData , cbfunc  ){
			var self = this,
				action = action || 'del',
			    noPrefixId = spotData.id.replace(/^[a-zA-z]/,''),   //id可能有一个前缀't'
				reqAction = (action == 'add' ? 'guide_fav_add' : 'guide_fav_del');
			
			if( action == 'add' ){
				if(  this.jqView.find('ul.selected-list #'+noPrefixId )[0]  || $('ul.trip-tags #trip_tags_t'+noPrefixId)[0] ||  $('ul.trip-tags #trip_tags_'+noPrefixId)[0] )
					return MB.alert('提示','该景点已添加。');
			}
			
			
			Req.jsApiCall('center',reqAction,{id: noPrefixId}, function(rst){
				if(rst.isOk()){
					self[ action + 'Callback']( spotData );
					cbfunc &&　cbfunc(　spotData　);
				}else MB.alert('提示',rst.getMsg());
			})
		},
		/**
		 * @cfg delCallback 由reqSetSpot调用
		 * @param {Object} spotData {id: xxx, name: 'xxx'}
		 */
		delCallback : function( spotData ){
			var $tripBox = this.jqView;
			
			$tripBox.find( '#t'+ spotData.id +':checkbox' ).attr('checked', false).parent('label').removeClass('selected');
			$tripBox.find( '#li_'+spotData.id ).remove();
			
			//开通码头里的处理
			var $count = $('#spotCount');
			$count.html( Math.max( (+$count.html())-1, 0) );
		},
		/**
		 * @cfg addCallback 由reqSetSpot调用 
	     * @param {Object} spotData {id: xxx, name: 'xxx'}
		 */
		addCallback : function( spotData ){
			var $tripBox = this.jqView;
			
			$tripBox.find( '#t'+ spotData.id +':checkbox' ).attr('checked', true).parent('label').addClass('selected');
			$tripBox.find('ul.selected-list').append( T.parse('spotsItem', spotData ) );
			
			//开通码头里的处理
			var $count = $('#spotCount');  
			$count.html( +$count.html()+1 );
		},
		//显示换一批按钮
		showChangeBtn : function( show ){
			this.jqView.parent().find('#btn_change')[ show ? 'removeClass' : 'addClass' ]('hidden');
		},
		
		// cfg  searchSelect 选择(点击 or enter) 搜索结果的某一行 的回调
		searchSelect : function(e, row){
			this.schControl.search.reset();
			var rid = row.id;
			this.reqSetSpot('add', {id: rid, name: row.name} );		
			this.schControl.search.display(0);
			$(this.schControl.inputor).focus();
		},
		
		schControl : null,
		//搜索框
		setSearchBox : function(){
			var self = this;
			$('#inp_search').addClass('style-normal');
			self.schControl = X.use('search', {
				inputor : $('#inp_search', this.jqview),
				defaultText : '搜景点',
				view : $('body')[0],
				unChange: true,
				focusCS : 'style-focus',
				catchClick: true,
				onEnter : Util.bind(self.searchSelect, self),
				affixfun: function(){ 
					var inpOffset = this.inputor.offset();
					$(self.schControl.search.view).css({
						left: inpOffset.left,
						top: !win.XMLHttpRequest ? inpOffset.top+16 : inpOffset.top+26
					})
				}
			});
		}
	}
	$.extend( inst, cfg, true );
	inst.init();
	return inst;
})

    	
X.reg('manageTrip', function( cfg ){
	cfg = cfg || {};
	var inst = X.use('Dlg',{
		cs : 'win-add-trip win-fixed',
		appendTo : "body",
		title: '添加难忘旅途',
		closeable: true,
		dlgContentHtml : 'tripManage',
		innerControl : null,   //indelibleTrip控件
		onViewReady: function(){
			var self = this;
			self.jq('#xwb_dlg_ct').removeClass('clear');
			this.innerControl = X.use('indelibleTrip', $.extend( {jqView : this.jq('#tripBox')}, cfg) );
			this.jq('#btn_ok, #btn_cancel').click(function(){
				self.close();
				return false;
			});
		}
	});
	X.reg('manageTrip',inst,true);
	return inst;
})

X.reg('groupLayer',function(){
	var box = X.use('Box',{
		cs : 'win-add-group win-fixed',
		contentHtml : 'groupLayer',
		appendTo : document.body,
		title: '添加小组',
		closeable : true,
		mask: true,
		onViewReady : function(){
			var self = this;
			self.jq('#btn_close').click(function(){
				self.close();
			});
			//this.jq().css('width','auto');
			var $ul = self.jq('#list_s1');
			Req.jsApiCall('groupApi','get_list',{},function(rst){
				if(rst.isOk()){
					var data = rst.getData(),
						html = '';
					for(var i in data){
						var d = data[i];
						d.joined == 1 ? $.extend(d, {_joined: 1,type:2}) : $.extend(d, { _join: 1,type:2});
						html += T.parse('groupLayerItem', d );
					}					
					html && $ul.html(html);
				}
			});
		},
		onclose : function(){
			this.jq('#nullTip').addClass('hidden');
		}
	});
	
	X.reg('groupLayer',box, true);
	
	return box;
})

//群组对象的命名空间
//var Group = X.mod.Group = {};
    
//成员列表，管理成员:剔除、黑名单功能
X.reg('GroupMemberList', Util.create(Base, {
    autoRender : TRUE,
    actionMgr : true, 
    
    /**
    * 鼠标飘过时要显示的元素
    */
    mouseoverItems : '',
    
    onactiontrig : function(e){
        var data = e.data;
        switch (data.e) {
        case 'del':
            this.delMember(e);
        break;
        case 'bl': //添加到黑名单
            this.addBlack(e);
        break;
        
        //remove group blacklist
        case 'rmgpbl' : //解除黑名单 
            this.removeBlack(e);
        break;
        }
    },
    
    removeBlack : function(e){
        MB.anchorConfirm(e.src, '确定解除该黑名单吗？', function(btn){
            if (btn == 'ok') {
                var gid = e.get('gid'),
                    uid = e.get('u');
                    
                Req.memberDelBlack(gid, uid, function(r){
                    if (r.isOk()) {
                        var $el = $(e.getEl('u')),
                            $list = $el.parent();
                        $el.fadeOut('slow', function(){
                            $el.remove();
                            if (!$list.find('li').length)  Refresh();
                        });
                    } else {
                        MB.alert('提示', r.getMsg());
                    }
                });
            }
        });
    },
    
    /**
    * 删除群组成员
    */
    delMember : function(e) {
        MB.anchorConfirm(e.src, '是否该成员剔除？', function(btn){
            if (btn == 'ok') {
                var gid = e.get('gid'),
                    uid = e.get('u');
                    
                Req.memberDel(gid, uid, function(r){
                    if (r.isOk()) {
                        //console.log(r.getData());
                        Refresh();
                    } else {
                        MB.alert('提示', r.getMsg());
                    }
                });
            }
        });
    },
    
    addBlack : function(e) {
        MB.anchorConfirm(e.src, '是否将他加入黑名单？', function(btn){
            if (btn == 'ok') {
                var gid = e.get('gid'),
                    uid = e.get('u');
                    
                Req.memberAddBlack(gid, uid, function(r){
                    if (r.isOk()) {
                        //console.log(r.getData());
                        Refresh();
                    } else {
                        MB.alert('提示', r.getMsg());
                    }
                });
            }
        });
    },
    
    onViewReady : function() {
        //搜索框聚焦效果
        //this.jq('input.input-txt').focusText('搜索成员名');
        
        //用于记录鼠标正在哪个会员头像之上
        var $li_over, 
            mouseoverItems = this.mouseoverItems;
        
        //检查target是否在$li_over上
        function isInArea(target) {
            return $li_over && ($li_over[0] === target || $.contains($li_over[0], target));
        }
        
        //监听鼠标mouseover事件，显示易除和黑名单操作按键
        if (mouseoverItems) {
            this.jq('ul.list-s1').mouseover(function(e){
                var target = e.target;
                
                //如果当前缓存还在$li_over范围内，忽略掉
                if (isInArea(target)) return;
                
                var li = $li_over = $(target).parentFind('li', this);
                if (li) {
                    $li_over = $(li);
                    $li_over.find(mouseoverItems).cssDisplay(1);
                }
            })
            .mouseout(function(e){
                var target = e.target, related = e.relatedTarget, hide = true;
                if (related) {
                    if (isInArea(related)) {
                        hide = false;
                    }
                }
                //if ($.contains(this, ))
                if (hide && $li_over) {
                    $li_over.find('a.delete,a.blacklist').cssDisplay(0);
                    $li_over = null;
                }
            })
        }
    }
}));

//群组信息设置
X.reg('GroupInfo', Util.create(Base, {
    actionMgr : TRUE,
    
    onViewReady : function() {
        
    },
    
    onactiontrig : function(e){
        var data = e.data;
        switch (data.e) {
        case 'save':
            e.lock(1)
            var desc = this.jq('textarea').val();
            Req.saveGroupInfo(e.get('gid'), {desc : desc}, function(r){
                if (r.isOk()) {
                    MB.success('提示', '保存成功!');
                } else {
                    MB.alert('提示', r.getMsg());
                }
                e.lock(0);
            });
        break;
        
        case 'reset':
            this.jq('form')[0].reset();
            this.jq('textarea').focus();
        break;
        }
    }
}));

//添加印象
X.reg('addImpress',function( cfg ){
	var box = X.use('Box',$.extend( {
		cs : ' arrow-t win-form win-form-s1 win-impress',
		contentHtml : 'impressEditArea',
		boxOutterHtml : '<div class="arrow"></div>',
		appendTo : document.body,
		tagCache : {},
		showTag : function(d){
			var tag = d.tag;
				sli = [];
			for(var i=0,l=tag.length;i<l;i++)
				sli.push( '<a href="#" rel="e:ct">'+Util.escapeHtml(tag[i].tag)+'</a>' );
			sli.length>0 && this.jq('#taglist').html(sli.join('')).removeClass('hidden');
		},
		setData : function( img_id, yj_id ){
			this.data = {'img_id': img_id,  'yj_id': yj_id};
			return this;
		},
		getData : function(){
			this.data.tag = this.jq('#inp_tag').val();
			this.data.exp = this.jq('#ta_exp').val();
			this.data.comments = this.data.exp || '添加到我的印象啦,我也去过这里';
			return this.data;
		},
		onViewReady: function(){
			var self = this;
			self.jq().css('position','absolute');
			self.jq('#inp_tag').blur(function(){
				self.checkTagText();
			}).focus(function(){
				var imgid = self.getData().img_id;
				if( !self.tagCache[imgid] ){
					Req.jsApiCall('center','hot_tags',{id: imgid, count: 5},function(r){
						if(r.isOk()){
							var data = r.getData()[0];
							self.tagCache[imgid] = data;
							self.showTag(data);
						}
					},'POST');
				}else self.showTag( self.tagCache[imgid] );
			});

			self.jq('#ta_exp').keydown(function(){  self.checkExpText(); })
							  .focus(function(){  self.jq('#taglist').addClass('hidden'); })
			self.jq('#confirm').click(function(e){
				var param = self.getData();
				if( !param.tag ){
					MB.alert('','标签不能为空!');
					return false;
				}
				else if( self.checkTagText()<0 )
					return false;
				Req.jsApiCall('center','impress_create', param,function(r){
					if(r.isOk()){
						self.addSucced(param, r);
					}else MB.alert('',r.getMsg());
					self.close()
				},'POST');
				return false;
			});
			self.jq('#cancel').click(function(){
				self.close();
				return false;
			});
			X.use('action').reg('ct',function(e){
				self.jq('#inp_tag').val(e.src.innerHTML);
				self.jq('#taglist').addClass('hidden');
				return false;
			})
		},
		checkTagText: function(){
			var lw = Util.calWbText(this.jq('#inp_tag').val(), 6);
			lw<0 ? this.jq('#tagWarn').removeClass('hidden') : this.jq('#tagWarn').addClass('hidden');
			return lw;
		},
		checkExpText: function(text){
			var $lwElm = this.jq('#lessWord');
				lw = Util.calWbText(this.jq('#ta_exp').val(), 140)
			$lwElm.html(lw);
			lw<0 ? $lwElm.addClass('tips-on') : $lwElm.removeClass('tips-on');
			return lw;
		},
		//can override
		addSucced: function( data, resObj ){
			if( X.getCfg('page') == 'center.detail' ){  //如果是详细页，直接刷页面
					location.reload(1);
					return false;
			}
		
			var $imItem = $('#im_id_'+data.img_id);
			$imItem.find('span.add-my-mem').replaceWith('<span class="add-my-mem"><em>印象已添加</em><i></i></span>');
			
			var $tags = $imItem.find('div.ta-tags').children('a');
			if($tags.length<3){
				var isExist = false;
				for(var i=0;i<$tags.length;i++){
					if( $tags[i].innerHTML == Util.escapeHtml(data.tag) )
						isExist = true;
				}
				!isExist && $tags.parent().append('<a class="tag-s'+Math.ceil(Math.random()*3)+'" href="#">'+Util.escapeHtml(data.tag)+'</a>');
			}
			
			
			data.time =  new Date().toLocaleTimeString();
			data.src =  $('#userLink img')[0].src;
			data.exp =  Util.escapeHtml(data.exp);
			data.tag =  Util.escapeHtml(data.tag);
			$imItem.find('div.user-desc').html( T.parse('impressUserPic', data ) );
		},
		onclose: function(){
			this.jq('#inp_tag').val('');
			this.jq('#ta_exp').val('');
		},
		show: function( anchorElm ){
			X.ui.Base.prototype.display.call(this,1);
			this.anchor(anchorElm,'bl');
			
			var offset = $(anchorElm).offset(),
				targetTop = offset.top + 30,
				selfHeight = 224,
				st = $(document).scrollTop(),
				ch = Util.getClientHeight();
			var diff = targetTop + selfHeight -  st - ch;
			if( diff > 0 ){
				$('html,body').animate({'scrollTop': st+diff},'slow');
			} 
		}
	}, cfg) );
	X.reg('addImpress',box, true);
	return box;
})

	//上传照片组件
	ui.UpoadImage= X.reg('UpoadImage', Util.create(Base, {
		uploader:NULL,
		
		tipBox:NULL,
		
		checkImg : function(fileName){
			var pieces = fileName.split('.');
			return pieces.length && $.inArray(pieces.pop().toLowerCase(), ['jpg', 'png', 'gif','jpeg']) !== -1;
		},
		
		change:function(fileVal){
			if(fileVal && !this.checkImg(fileVal)){
				MB.alert('','只支持 jpg、png、gif 的图片。');
				this.jqForm.reset();
	//			$('#xwb_Shareimg_file').val('');
				return;
			}
			if(this.uploadBefore)	this.uploadBefore();
			this.getUploader().upload();
		},
		
		getUploader : function(){
			var url = this.url || Req.mkUrl('jsApi/weiboApi','uploadImg');
			if(!this.uploader)
				this.uploader = X.use('Uploader', {
					form:this.jqForm, 
					action :url,
					onload:Util.getBind(this, 'onUploadLoad')
				});
			return this.uploader;
		},
		
		onUploadLoad: function(e){
			if(this.clear) this.fileInput.val('');
			//this.jqForm.reset();
			if (e.isOk()) {
				this.uploadAfter !=null && this.uploadAfter(e.getData());
			}else {
				var errStr="";
				MB.alert('提示', e.getMsg());
				this.uploadError && this.uploadError();
			}
		}
	}));

	
//拖动组件
ui.DragBase = Xwb.reg('DragBase',Util.create(Base, {
	items : [] //拖动对象
	,parent : null//拖动对象级
	,dlagIngCls : 'dlaging'　　//拖动体样式
	,cp : []//每个可拖动对象位置
	,canDlagArea : null //可拖动区域
	,itemHeight : null　//拖动体高度
	,clone : false //拖动对象并带背景
	,sortAble : false //调整顺序
	,target : null //放置目标位置
	,movePart : $('body') //可拖动区域
	,targetInCls : 'targetIn'  //拖动体在放置目标上样式
	,pushPoint : function(item){
		this.cp.push({obj:item,offset:item.offset()});
	}
	,cloneTemp : '<div class="dlagnull hidden" ></div>'
	,initUI : function(e){
		var self = this;
		if(this.items.length){
			this.items.each(function(i){					
				var _t = $(this);
				self.pushPoint(_t);
				_t.mousedown(function(e){
					_t.data('md',true);
					Util.bind(self.mousedown, self)(e,_t);	
					self.movePart.bind('mousemove', function(e){
						Util.bind(self.mousemove, self)(e,_t);
					})		
				}).mouseup(function(e){
					_t.data('md',false);
					document.onmousemove = null;
					$('body').unbind('mousemove', self.mousemove);
					Util.bind(self.mouseup, self)(e,_t);
				});

				_t.data('index', i);
			})
			this.itemHeight = $(this.items[0]).height();
		}
	}
	
	,mousedown : function(e, dom){
		var off = dom.offset();	
		dom.data('cache',{cx:e.clientX, cy:e.clientY, left:off.left, index : dom.index(), gap: e.clientY - off.top});
		if(this.clone)
			this.insertClone = $(this.cloneTemp).insertBefore(dom);			
	}
	
	,mouseup : function(e, dom){
		this.stop(dom, e);
		if(this.clone){
			this.insertClone.remove();
			this.insertClone = '';	
		}
	}
	
	,mousemove : function(e, dom){			
		var cache = dom.data('cache');
		dom.css('position','absolute').offset({left:(e.clientX - cache.cx+ cache.left),top:e.clientY-cache.gap});
		dom.addClass(this.dlagIngCls);	
		if(this.clone){
			this.insertClone.cssDisplay(1);	
			this.sortAble && this.mathInsertNull(e);
		}

		if(this.target){
			this.moveTarget && this.moveTarget(this.isInTarget(dom, e), dom, this.target);
		}					
	}		
	
	,stop : function(dom, e){
		dom.removeClass(this.dlagIngCls);
		if(this.target){
			this.toTarget(dom, e);
		}else{
			if(this.reset){
				dom.removeAttr('style');
			}
		}
	}
	
	,isInTarget : function(dom, e){
		var tg = this.target;
		if(typeof tg == 'string')
			tg = $(tg);
		if(tg.length){
			var tgOff = tg.offset(), domOff = dom.offset(), maxL = tgOff.left+tg.width(), maxH = tgOff.top + tg.height();
			if(e.clientX>tgOff.left && e.clientX<maxL && e.clientY>tgOff.top && e.clientY<maxH){
				return true
			}
		}
		return false;
	}
	
	,moveTarget : function(isIn, dom){
		var tg = this.target;
		if(typeof tg == 'string')
			tg = $(tg);
		if(isIn){
			tg.addClass(this.targetInCls);
		}else
			tg.removeClass(this.targetInCls);
	}
	
	,toTarget : function(dom, e){		
		if(this.isInTarget(dom, e)){
			this.inTargetFn && this.inTargetFn(dom);
			this.moveTarget(false);
		}else{
			dom.removeAttr('style');
		}
	}
	,remove : function(){
		this.items.each(function(i){					
			var _t = $(this).unbind('mousedown').unbind('mouseup')
		});				
	}
	
}));

//拖动排序
Xwb.reg('DragSort',Util.create(ui.DragBase, {
	clone : true
	,sortAble : true
	,stop : function(dom){
		ui.DragBase.prototype.stop.call(this,dom);
		this.insert(dom);
	}
	
	,mathInsertNull : function(e){
		var min = this.parent.offset().top,  max = this.parent.height()+min, cur = e.clientY + this.itemHeight, cp = this.cp; 
		len = cp.length;			
		if(cur > max || cur < min) return;
		for(var i=0;i<len;i++){
			var item = cp[i], offset = item.offset;
			if(offset.top<e.clientY && offset.top>(e.clientY-this.itemHeight)){
				if(e.clientY+this.itemHeight/2>offset.top+this.itemHeight)
					this.setInsertNull(item.obj, 'a');
				else					
					this.setInsertNull(item.obj, 'b');
				break;
			}
		}
	}
	
	,setInsertNull : function(item, p){
		if(this.insertClone){
			if(p == 'b')
				this.insertClone.insertBefore(item);
			else
				this.insertClone.insertAfter(item);
		}
	}
	
	,insert : function(dom){
		dom.removeClass(this.dlagIngCls).removeAttr('style');		
		if(this.insertClone){
			var oldIndex = dom.data('cache').index, newIndex = this.insertClone.index();
			var newDom = this.insertClone.replaceWith(dom);
			if(oldIndex != dom.index()){
				this.sort && this.sort(oldIndex, newIndex, dom);
			};		
			var self = this;
			this.cp = [];
			this.parent.children().each(function(i){					
				self.pushPoint($(this));
			})
		}
		
	}
	
	,sort : function(oi, ni, dom){
		console.log('oldIndex:'+oi+' newIndex:'+ni);
		console.log(dom);
	}
}));




//简单分页(上一页,下一页)	
ui.SimplePage = X.reg('SimplePage', Util.create(Base, {
	view : '',
	actionMgr : TRUE,
	count : 20,
	pageSize : 5,
	totalPage : 4,
	prevCs : 'prev',
	prevHtml : '<a href="#" rel="e:p,t:u">上一页</a>',
	prevDiHtml : '<span>上一页</span>',
	nextCs : 'next',
	nextHtml : '<a href="#" rel="e:p,t:d">下一页</a>',
	nextDiHtml : '<span>下一页</span>',
	prevDiCs : 'prev-disable',	
	nextDiCs : 'next-disable',
	curPage : 1,   
    onactiontrig : function(e){
        switch (e.data.e) {
			case 'p':
				if(e.get('t') == 'u'){//上一页
					if(this.curPage>0) this.curPage--;					
				}else{//下一页
					if(this.curPage<this.totalPage) this.curPage++;			
				}
				this.setPage(e);
			break;
        }
    },
	onViewReady : function(){
		this.totalPage = Math.ceil(this.count/this.pageSize);
		this.setPageCs();
	},
	
	setPage : function(e){
		if(this.loadData){
			this.loadData(this.curPage, this.setPageCs);
		}else{
			this.setPageCs();
		}
	},
	
	setPageCs : function(){
		var prev = this.jq('.'+this.prevCs), next = this.jq('.'+this.nextCs);
		if(this.curPage > 1){
			prev.removeClass(this.prevDiCs);
			prev.html(this.prevHtml);
		}else{
			prev.addClass(this.prevDiCs);
			prev.html(this.prevDiHtml);
		}
		
		if(this.curPage + 1 <= this.totalPage){
			next.removeClass(this.nextDiCs);
			next.html(this.nextHtml);
		}else{
			next.addClass(this.nextDiCs);
			next.html(this.nextDiHtml);
		}
	},
	
	reset : function(count, curPage, pageSize){
		if(count == 0) $(this.view).cssDisplay(0);
		this.count = count;
		this.curPage = curPage || 1;
		this.pageSize = pageSize || this.pageSize;
		this.totalPage = Math.ceil(this.count/this.pageSize);
		this.setPageCs();
	}
}));

//RTE 富文本编辑器
X.reg('GroupPostEditor', Util.create(Base, {
    autoRender : true,
    
    //编辑器的DOM ID
    id : null,
    
    tmpid : 0,
    
    imgs : null,
    
    onViewReady : function() {
        
        var basePath = getCfg('basePath'),
            cfg = {
                controls_rte: {
                        image : {
                            hint : "图片",
                            exec : 'youji_image',
                            txt : '图片',
                            tags : [ "img" ]
                        },
						face : {
							hint : '表情',
							txt : '表情',
							exec : 'youji_face',
							tags : ['img']
						}
						
                },
                controls_html: X.html_toolbar,
                width:503,
                height:200,
                youjiEditorToolBarStyle: true,  //
				css:[ Xwb.cfg.basePath + 'js/rte/post_reset.css' ],   //重置样式
                resizer : false,
                //ubbMode:false,
                viewCodeButton:false,
                autoHeight:true
            };
            
        this.css = [ basePath + 'js/rte/default.css' ],
        
        $.extend(this, this.jq().rte(cfg));
        
        //用于get方法获取RTE对象
        this.id = this.jq().attr('id') || '0';
        
        var panel, self = this;
        
        function getPhotoPanel() {
            if (!panel) {
                panel = X.use('RtePhotoInsertPanel', {xRte : self});
            }
            return panel;
        }
        
        RTE.youji_image = function() {
            getPhotoPanel().display(1);
        }
		
		RTE.youji_face = function(src) {
			//console.log(this.iframe_doc);
			var self = this;
			X.use('emotion')
			.setHandler(
				function(text, evt){
					var elface = evt.src;
					//_this.insertNetImg($(elface).find('img').attr('src'), 25, 25);
					self.insertHTML('<img face="'+text+'" src="'+$(elface).find('img').attr('src')+'"/>');
				}
			)
			.showAt(src);
		}
        
        this.imgs = [];
    },
    
    get : function() {
        return this[this.id];
    },
    
    //检查图片是否已经在数据里
    existsUrlPhoto : function(url) {
        var imgs = this.imgs, img;
        
        for (var i in imgs) {
            img = imgs[i];
            if (!img) continue;
            if (img.type == 'url' && img.url == url)
                return 1;
        }
        
        
        return 0;
    },
    
    addPhotoData : function(type, data) {
        var imgs = this.imgs;
        switch (type) {
        case 'url':
            imgs.push({type : 'url', url : data});
        break;
        
        case 'BASE64':
        
        break;
        
        default:
            imgs.push(data);
        }
    },
    
    getTmpID:function(){
        return ++this.tmpid;
    },
    
    //插入网络图片
    insertNetImg : function( url, w, h ) {
        var tmpImgID = this.getTmpID(), width = '', height = '', editer = this.get();
        if( w )   
            width = 'width="'+ w +'"';
        if( h )      
            height = 'height="'+ h +'"';
        editer.insertHTML('<div><img src="'+ url +'" id="netPic_'+ tmpImgID +'" '+width+' '+height+'/></div><p>&nbsp;</p>');
        this.blankLineHack( $(editer.iframe_doc).find('#netPic_'+tmpImgID) );
        
        if (!this.existsUrlPhoto(url))
            this.addPhotoData('url', url);
    },
    
    //为了产生一个空行,并在个浏览器表现一致
    blankLineHack : function( $img ) {
        if( $.browser.msie ) { // IE 7,8 hack
            var  $np = $img.parent().next();
            if( $np[0].nodeName != 'P' ){
                $("<p>&nbsp;</p>").insertBefore($np);   //IE下有时第一张图片下面没有空行出现(不是换行)
                return ;
            }
            var $nbr = $np.next();
            if( $nbr.next()[0] && $nbr[0].nodeName === "BR" ){
                $nbr.remove();  //将IE自动产生的<br/>干掉
            }
        }
    },
    
    /*处理插入单个图片的兼容问题。由于单个插入浏览器会根据附近的格式作一些处理，
      比如空的<p/>将不占位，要<p>&nbsp;</p>才占位，<br/>在火狐下才占位
    */
    batchInsertImg: function( rstArr ){
        if( !rstArr ) return ;
        var img_htmls = [], editer = this.get();
        for(var o; o = rstArr.shift(); ){
            var data = o.getData()[0];
            var pic = data.web_pic,
                imgWH = pic.width > pic.height ? 'width="300"' :'height="300"';
            imgWH = Math.max(pic.width,pic.height) > 300 ? imgWH : '';
            //this.AlbumsAllList[pic.url] = data;
            this.addPhotoData(pic.type, data);
            img_htmls.push('<div><img src="'+pic.url+'" ' + imgWH +' /></div><p>&nbsp;</p>');
        }
        editer.insertHTML(img_htmls.join(''));
    },
    
    //返回包含的图片数据信息
    getImgData : function() {
        return this.imgs;
    }
}));

//小组发帖
mod.GroupPost = X.reg('GroupPost', Util.create(Base, {
    rte : null,
    
    autoRender : true,
    
    //模式 0：新发表 1：编辑
    mode : 0,
    
    //原ID（编辑状态下才有）
    _id : '',
    
    //原内容（编辑状态下才有）
    _content : '',
    
    _title : '',
    
    checkEnabled : true,
    
    onViewReady : function() {
        var rte = this.rte = X.use('GroupPostEditor', {
            view : this.jq('#editor').get(0)
        });
        
        //绑定save的action        
        var action = X.use('action');
        
        //保存小组帖子
        action.reg('gpostsave', Util.bind(this.savePost, this));
        
        //绑定beforeunload
        $(win).bind('beforeunload', Util.bind(this.saveCheck, this));
    },
    
    //检查是否需要保存
    saveCheck : function() {
        if (!this.checkEnabled) return;
        
        if (this.mode == 0) {
            var editor = this.rte.get(),
                ubbcontent = editor.get_content(),
                vtitle = $('#title').val();

            if (!this.isBlankUbb(ubbcontent) || vtitle) {
                return '你的帖子还没保存，是否要离开？';
            }
        } else if (this.mode == 1) {
            if (this.hasChange()) {
                return '你的帖子还没保存，是否要离开？';
            }
        }
    },
    
    setId : function(id) {
        this._id = id;
        return this;
    },
    
    //设置初始化数据，如：id, imgs, content
    setData : function(data) {
        data = data || {};
        var imgs = data.img_data,
            content = data.text,
            id = data.id,
            rte = this.rte,
            vtitle = data.title;
        
        if (imgs && rte) {
            $.each(imgs, function(i, img){
                rte.addPhotoData(img.type, img);
            })
        }
        if (content) this.setContent(content);
        if (id) this.setId(id);
        
        //console.log(this);
        
        return this;
    },
    
    //设置内容 ubb格式
    setContent : function(content){
        var editor = this.rte.get();
        editor.set_content(ubb.bbcode2html(content));
        this._content = content;
        return this;
    },
    
    //检查内容是否为空白字符
    isBlankUbb : function(contentTxt)  {
        var ubbsource = $.trim(contentTxt);
        if (!ubbsource) return false;
        return !ubbsource.replace(/\[br\]|\[p\]|\[\/p\]|\[ns\]/g, '').length;  //普通内容
   },
   
   //用于编辑模式时，检查内容是否有改变
   hasChange : function() {
       var editor = this.rte.get(),
            ubbcontent = editor.get_content(),
            vtitle = $('#title').val();
       //console.log(ubbcontent);
       //console.log(this._content);
       if (ubbcontent != this._content) {
           return true;
       }
       
       if (vtitle != this._title) {
           return true;
       }
       
       return false;
   },

    //保存帖子
    savePost : function(e) {
        var editor = this.rte.get(),
            ubbcontent = editor.get_content().replace(/\r|\n/g,''),   //去除制表符，换行符
            vtitle = $('#title').val(),
            self = this;
		
        //检查数据
        if (!$.trim(vtitle)) {
            MB.tipWarn('标题不能为空。');
            $('#title').focus();
            return;
        }
        
        if (this.isBlankUbb(ubbcontent)) {
            MB.tipWarn('内容不能为空。');
            return;
        }
        
        var data = {
            text : ubbcontent,
            title : vtitle
        };
        
        var mode = this.mode;
        
        if (mode) { //编辑
            var id = this._id ;
            data.id = id;
        } else {
            var gid = $('#group_name').val();
            data.gid = gid;
            
            //分享到
            var shares = [];
            $('#share').find('input:checked').val(function(){
                shares.push(this.value);
            });
            if (shares.length) {
                data.share = shares.join(',');
            }
        }

        var img_data = this.rte.getImgData();
        if (img_data){
            data.img_data = $.toJSON(img_data);
        }
        
        e.lock(1);
        Req.saveGroupPost(data, function(r){
            if (r.isOk()) {
                MB.success('提示', mode ? '保存成功.' : '发表成功.');
                self.checkEnabled = false;
				var HASH = '';
				if( r.getData().notice )
				    HASH = '#npt';   //new post hash, 发表新话题奖励游币提示
                win.location.href = r.getData().redirect_url + HASH;
            } else {
                MB.error('提示', r.getMsg());
                e.lock(0);
            }
        });
    }
}));

//分享给好友(选择好友)
ui.ShareByChoose = X.reg('ShareByChoose', Util.create(Base,{
	onViewReady : function() {
		this.initSearcher();               
		var $currService = this.jq('#current_service');
		var cls = $currService.attr('class').split('-');
		switch (cls[1]) {
		case 'sina':
		case 'qq':
			this.type = cls[1];
		break;
		case 'rr':
			this.type = 'renren';
		break;
		}
	},
	
	cache : {},
	
	type : 'sina',
	
	users : {
		data : [],
		
		length : 0,
		
		add : function(id, u) {
			if (this[id]) return;
			
			var index = this.data.length;
			this.data[index] = u;
			this[id] = index;
			this.length++
		},
		
		del : function(id) {
			//debugger;
			this.data.splice(this[id], 1);
			//this.data[this[id]] = null;
			delete this[id];
			//console.log('after delete : ',id, this[id]);
			this.length--;
		},
		
		exist : function(id) {
			//console.log('is exists, ', id, this[id]);
			return this[id] !== undefined;
		},
		
		getData : function() {
			var data = [];
			
			$.each(this.data, function(i, u){
				if (u) data.push(u);
			})
			
			return data;
		}
	},
	
	//进度条
	_progressBar : null,
	progressBar : function() {
		if (!this._progressBar) {
			this._progressBar = X.use('ProgressBar');
		}
		
		return this._progressBar;
	},
	
	actionMgr : true,
	onactiontrig : function(e) {
		var data = e.data;
		switch (data.e) {
		case 'delu'://删一个好友
			var id = e.get('bid'),
				type = e.get('type'),
				key = type + '_' + id;
			this.users.del(key);
			if (this.users.length < 10) {
				this.enableInput(1);
			}
			$(e.src).parent().remove();
		break;
		
		case 'showtype': //选择搜索类型
			this.toggleTypes();
		break;
		
		case 'seltype':
			this.jq('#current_service').attr('class', data.cls);
			this.type = data.t;
			this.toggleTypes(0);
		break;
		
		//分享游记
		case 'shareYouji':
			e.lock(1);
			this.progressBar()
			.setText('正在发布')
			.progress(1)
			.show();
			
			var users = this.users.getData(),
				sharetext = this.jq('textarea').val(),
				shareyoujiid = this.youji_id
				self = this;
			
			function doShare(pic) {                        
				pic = pic || '';
				var sharedata = {
					youji_id : shareyoujiid,
					pic_bin : pic,
					text : sharetext,
					users_at : $.toJSON(users)
				}
				
				Req.shareYouji2(sharedata,function(r) {
					if (r.isOk()) {
						win.location = $('a.skip').attr('href');
					} else {
						self._progressBar.hide();
						MB.alert('提示', r.getMsg());
						e.lock(0);
					}
					
				});
			}
			
			var pl = X.use('pipeMgr').getByType('youji.sharePic');
			if (pl) {
				var ui = pl.getUI();
				if (ui.imgs && ui.imgs.length){
					ui.callBackFunc['imgString'] = doShare;
					ui.flashCall('jpgCode');
					return;
				}
			}
			
			doShare();
			
			break;
			
			case 'share' :	
				var users = this.users.getData(),
				sharetext = $.trim(this.jq('textarea').val()),
				self = this,
				id = e.get('pid');
				
				var us = [], types = {'sina':1, 'qq':2, 'renren':3};
				$.each(users, function(i, u){
					//var info = {type:u.type, nick:u.nickname, face:u.profile_img, uid:u.bid};
					var type = types[u.type] || 0;
					if (u) us.push({type:type, nick:u.nickname, face:u.profile_img, uid:u.bid});
				})
				
				
				if(users.length == 0){
					MB.alert('','请选择要分享的好友');
					return;
				}
				if(Util.byteLen(sharetext)>100){
					MB.alert('','留言不能超过100个字符,50个汉字')
					return;
				}
				e.lock(1);
				this.progressBar()
				.setText('正在发布')
				.progress(1)
				.show();
				
				Req.postcardShare(id,sharetext,$.toJSON(us) ,function(r) {
					if (r.isOk()) {
						win.location = r.getData().url;
					} else {
						self._progressBar.hide();
						MB.alert('提示', r.getMsg());
						e.lock(0);
					}					
				});
				
				
			break;
		}
	},
	
	toggleTypes :  function(show){
		var $tlist = this.jq('#typesList');
		if ($tlist.length) {
			$tlist.cssDisplay(show === undefined ? !$tlist.cssDisplay(): show);
		}
	},
	
	//异步查询好友
	friendsReq : function(kw, cb) {
		
		var key = this.type + '_' + kw;
		
		if (this.cache[key]) {
			cb(this.cache[key]);
			return;
		}
		
		var self = this;

		if(this.type == 'local'){
			Req.searchLocalFriends(kw, function(e){
				if (e.isOk()) {
					var rst = e.getData();
					self.cache[key] = {k: kw, result: rst};
					cb(self.cache[key]);
				}
			});
		}else{
			Req.searchFriends(this.type, kw, 10, function(e){
				if (e.isOk()) {
					var rst = e.getData();
					self.cache[key] = {k: kw, result: rst};
					cb(self.cache[key]);
				}
			});
		}
	},
	
	enableInput : function(en) {
		this.jq('#friends_search').cssDisplay(en);
		this.jq('#friends_full').cssDisplay(!en);
	},
	
	addUser : function(user) {
		var id = user.type + '_' + user.bid;
		//console.log(!this.users.exist(id) , this.users.length);
		if (!this.users.exist(id) && this.users.length < 10) {
			user.type = this.type;
			var rel = Util.encodeKnV(user);
			var html = '<a title="'+user.nickname+'" rel="'+rel+'" href="javascript:void(0);" class="pic"><img src="'+user.profile_img+'"><i class="close" rel="e:delu"></i></a>';
			$(html).appendTo(this.jq('#avatars'));
			
			this.users.add(id, user);
			if (this.users.length >= 10) {
				this.enableInput(0);
			}
		}
	},
	
	initSearcher : function(){
		var $input = this.jq('#friends_search'),
			inst = this;
		this.type = Util.parseKnV(this.jq('#current_service').parent().attr('rel')).t;
		
		var search = X.use('search', {
			view : $input.parent()[0],
			viewTemp : 'autoComplete',
			defaultText : '输入好友昵称..',
			contextable : true,
			inputor : $input,
			sUrl : Util.bind(this.friendsReq, this),
			loadComplete : function(data){
				if (data.k == this.val) {
					this.showResult(data.result);
				}
			},
			
			showResult : function(list) {
				var $list = this.jq(), htmls = [];
				
				if (list.length) {
					var rel;
					$.each(list, function(i, l) {
						rel = Util.encodeKnV(l);
						htmls.push('<a href="#" rel="'+rel+'">'+l.nickname+'</a>');
					});
					
					$list.html(htmls.join(''));
				} else {
					$list.html('<a href="javascript:void(0);">没有找到好友...</a>');
				}

				if(list.length == 0){
					htmls.push('<p>没有找到好友</p>');								
				}
				$list.html(htmls.join(''));
			   
				//inst.jq('#droplist').cssDisplay(1);
				this.display(1);
			},
			
			children : 'A',
			
			onViewReady : function() {
				var $item = this.search.jq(), self = this;
				$item.click(function(e){
					e.preventDefault(true);	
					if(inst.users.data.length>9){
						MB.alert('','分享的好友不能超过10个');
						return;
					}
					var $target = $(e.target),
						rel = $target.attr('rel');
					if (e.target.tagName.toUpperCase() == 'A' && rel) {
						var data = Util.parseKnV(rel);
						data.type = inst.type;
						inst.addUser(data);
						self.jq('#droplist').cssDisplay(0);
						self.search.reset();
					}
				});
				
				function selectItem(up) {
					var $results = $item.find('a[rel*=bid]'),
						len = $results.length;
					if (!len) return;
					
					var $curr = $item.find('.cur');
					var index = $curr.index();
					
					if (up) {
						index = --index < 0 ? len-1 : index;
					} else {
						index = ++index > len-1 ? 0 : index;
					}
					
					$curr.removeClass('cur');
					$results.eq(index).addClass('cur');
				}
				
				this.inputor.keydown(function(e){
					switch (e.keyCode) {
					case 38:
						selectItem(1);
					break;
					
					case 40:
						selectItem(0);
					break;
					
					case 13:
						var $curr = $item.find('.cur');
						if ($curr.length) {
							var rel = $curr.attr('rel');
							var data = Util.parseKnV(rel);
							data.type = inst.type;
							inst.addUser(data);
							self.jq('#droplist').cssDisplay(0);
							self.inputor.val('');
						}
					break;
					}
				})
			}
		});
	}
}))

//直接调用第三方分享
mod.trdShare = {
	type2name : {
		1: 'sina',
		2: 'qq',
		3: 'renren'
	},
	trdShareUrl : {
		1: 'http://service.t.sina.com.cn/share/share.php',
		2: 'http://share.v.t.qq.com/index.php',
		3: 'http://widget.renren.com/dialog/share' //http://share.renren.com/share/buttonshare.do'
	},
	trdParam : {
		1: {
			title: '',  //内容
			url: 'http://www.ziyou.com',
			appkey:	'',
			pic: ''
		},
		2: {
			c:	'share',
			a:	'index',
			title:	'自游网 分享代码 - 自游网',
			url:	'http://www.ziyou.com',
			appkey:	'',
			pic: ''
		},
		3 : {  //人人分享widget调用参数
			// resourceUrl : '',
			// pic : '',
			// title : '',
			// description : ''
		}
	},
	
	//返回第三方分享的url
	makeShareUrlByTrdType : function( type, relData ){
		var p = this.trdParam[type];
		var d = this.pick_upContentAndPicFromPage( X.getCfg('page'), type, relData );
		if( type < 3 ) {
			p.appkey =  ( type == 1 ? X.getCfg('sinaAppKey') : X.getCfg('tcAppKey') );
			p.url = location.href;
			if( type == 1 ) // sina 只能传递一张照片
				d.pic[0] ? p.pic = d.pic[0] : p.pic = '';
			else
				p.pic = d.pic.slice(0,4).join('|');
			
			p.title = encodeURIComponent( d.content );
		}else {
			if( relData.imgUrl ){
				p.pic = encodeURIComponent(d.pic[0]);
				p.title = encodeURIComponent(d.content.substring(0,20)+'...');
				p.resourceUrl = encodeURIComponent(location.href);
				p.description = encodeURIComponent( d.content );
			}
			else{
				p = {
					title: encodeURIComponent( d.content ),
					link: location.href
				}
			}
		}
		
		var parStr = '';
		for(var i in p){
			parStr += '&'+i + '=' + p[i];
		}
		//p.pic = this.pickUpPicFromPage( X.getCfg('page') ) || '';
		return this.trdShareUrl[type] + '?' + parStr.substring(1);
	},
	/* 从页面抓取内容,text and img
	 * @return {object} paramData 
			{
				content: '',
				pic: []   //必须是数组
			}
	 */
	pick_upContentAndPicFromPage : function( page, trdType, relData ){
		var self = this, 
			paramData = {
				content: '',
				pic: []   //必须是数组
			},
			clen = 80;
		if( page == 'youji' ){
			var yjData =  X.getCfg('youji'),
				content = yjData.text.replace(/\[img[^[]*][^\[]*\[\/img]/ig,'').replace(/\s|\r|\n|\r\n/ig,'')
									 .replace(/\[\/?[^[]*]/ig,'');
			
			content = content || '';
			
			var postType = 'yj';
			if( relData && relData.postType )
				postType = relData.postType;

			if( (yjData && yjData.create_type !== 'basic') || postType == 'yjsd' ||  content.length < 30 ){
				var tn =  X.mod.trdShare.type2name[trdType] || 'sina';

				Req.jsApiCall('public','getShareString', {type: postType, id: getCfg('youji').id, service: tn}, function(r){
					if( r.isOk() ){
						var d = r.getData();
						content = d.text;
						//paramData.pic = d.pic;
					}
				},'POST', {async: false});
			}
			else{
				if( content.length > clen )
					content = content.substring(0,clen-3)+'...';
				var title = '《'+ $.trim($('.tit-in').html().split('<')[0]) + '》',
					prefixText = '我发表了游记' + title + ': ';
				if( $('a.user_card').attr('rel').substring(2) != X.getUid() ){
					var author = $('a.user_card').html();
					prefixText = '分享@'+ author +' 的自游网游记' + title + ': ';
				}
				content = prefixText + content + ' ' + location.href + '（分享自@自游网旅游攻略）'
			}
			paramData.content = content;
			
			if( postType == 'yjsd' )
				paramData.pic = [ relData.imgUrl ];
			else {
				var imgData = yjData.img_data;
				for(var i=0;i<imgData.length;i++) 
					paramData.pic.push( imgData[i].web_pic.url );
			}
		}
		else if( page == 'spots.guide' ){
			var sname = $('div.bread-crumb a[href*=detail]').html(),
				desc = $('div.raider-cont>div.section:lt(2)>div.desc').text();
			desc = $.trim(desc);
			if( desc.length > 30 ){
				if( desc.length > clen )
					desc = desc.substring(0,clen-3)+'...';
				else 
					desc = desc.substring(0,clen);
			}
			
			paramData.content = '自游网#'+ sname +'攻略#：'+ sname +'，'+ desc + ' ' + location.href + '（分享自@自游网旅游攻略）'

			var $imgs = $('#container img'),
			len = $imgs.length > 40 ? 40 : $imgs.length;
			for(var i=0;i<len;i++){
				paramData.pic.push( $imgs[i].src );
			}
		}
		else if( /space.footmark|journey.hasBeen|journey.wantTo/ig.test( page ) ){
			var shareType = 'myfm',
				id = X.getUid(),
				m = location.href.match(/id[-=](\d+)/);
			if( m && m[1] && m[1] != X.getUid() ){
				shareType = 'tafm';
				id = m[1];
			}
			Req.getShareString(shareType, id, function(r){
				if( r.isOk() ){
					var d = r.getData();
					paramData.content = d.text;
					if( d.pic ) paramData.pic = [d.pic];
				}
			},{async: false});
		}
		else if(page === 'group.topic'){
			var tt = $('div.tour-title-s1 h1.tit-in').html() || '',
				summary = $.trim($('div.post-cont').text());
			if( tt )
				tt = '《'+ tt +'》';
			if( summary.length > 30 ){
				if( summary.length > clen )
					summary = summary.substring(0,clen-3)+'...';
				else 
					summary = summary.substring(0,clen);
			}
			paramData.content = '分享自游网小组帖子'+ tt + '：' + summary + ' ' + location.href;
		
			$('div.post-cont img').each(function(i,item){
				paramData.pic.push( $(item)[0].src );
			});
		}
		else if( /postcard.detail/ig.test(page) ){
			var $cardBox =  $('div.postcard-detail');
			var cardData = Util.parseKnV( $cardBox.attr('rel') );

			var prefixStr = '我在自游网寄出了一张'+ (cardData.spot || '') +'的明信片：'

			var m = $('.user-pic a')[0].href.match(/id[-=](\d+)/);
			if( (m && m[1] && m[1] != X.getUid()) || page === 'postcard.detail_inbox' )
				prefixStr = '分享自游网'+ (cardData.spot || '') +'的明信片：';
		
			paramData.content = prefixStr + '"' + (cardData.content || '') + '"';
			
			if( paramData.content.length > clen ){
				 paramData.content.length = paramData.content.substring(0,clen-3)+'...' 
			}
			paramData.content = paramData.content + ' ' + location.href + '（分享自@自游网旅游攻略）';
			
			$('a.card-img img').each(function(i,item){
				paramData.pic.push( $(item)[0].src );
			});
		}
		if( paramData.content == '' ){
			var dt = document.title.replace(/\[.+\]/ig,'')
			paramData.content = dt + ' ' + location.href;  //没指定分享文本的取当前页面的标题
			var $imgs = $('#container img'),
				len = $imgs.length > 40 ? 40 : $imgs.length;
			for(var i=0;i<len;i++){
				paramData.pic.push( $imgs[i].src );
			}
		}
		return  paramData;
	}
}
//全站分享
X.reg('shareBox',function( cfg ){
	var sharebox = X.use('Box',$.extend({
		//继承属性
		autoRender : TRUE,
		contentHtml : 'shareBox',
		cs : 'win-fixed win-share',
		title : '分享',
		appendTo : doc.body,
		closeable : TRUE,
		mask: TRUE,
		
		//扩展属性
		exceedCS : '',
		jqInputor : null, //输入框
		jqWarn : null,  //输入提示
		jqPicArea : null,   //图片操作的整个区域
		jqImgList : null,   //图片列表
		trd_id : '1',  //1.新浪 2.腾讯 3.人人 逗号分隔
		trd_title : {
			1: '分享到新浪微博',
			2: '分享到腾讯微博',
			3: '分享到人人网'
		},
		
		checkText : function(){
			return X.mod.PostBase.checkText.call(this);
		},

		onViewReady : function() {
			this.jqInputor = this.jq('textarea');
			this.jqWarn = this.jq('p.chenk-nun');
			this.SH = X.use('SelectionHolder', {elem:this.jqInputor[0]} );
			
			var self = this;
			this.jq('textarea').keyup(function(){
				self.checkText();
			});

			var jqPicArea = this.jqPicArea = this.jq('#picArea');
			var jqImgList = this.jqImgList = this.jq('ul.share-img');
			jqImgList.delegate('a','click',function(){
				var $t = $(this), $selElm = $t.find('span.select');
				
				if( $selElm[0] ) //当前是已选择状态
					$selElm.remove();
				else{
					var $spans = jqImgList.find('li span.select');
					if( $spans.length >= 5 ){  //最多选取5张的限制
						if( $spans[0] != $selElm[0] )
							$spans.eq(0).remove();
					}
					$t.append('<span class="select"></span>');
				}
				return false;
			});

			//底部action按钮
			
			self.lockPost = false;
			this.jq('a#btn_ok').click(function(){
				self.post();
				return false;
			});
			this.jq('a#btn_cancel').click(function(){
				self.close();
				return false;
			});
		},

		/* setType 设置分享类型
		 */
		setType : function( trd_type ){
			this.trd_id = trd_type;
			this.setTitle( this.trd_title[ trd_type ] );
			
			return this;
		},
		
		/* fillContent 填充内容
		 * @param {string} trdType 即trd_id
		 * @param {string} relData
		 */
		fillContent : function( trdType, relData ){
			//显示loading tip
			this.jq('#loading').removeClass('hidden');
			
			var data = this.pickUpDataFromPage( trdType, relData );
			
			//隐藏loading tip
			this.jq('#loading').addClass('hidden');
			
			//填充文本
			this.SH.setText( data.content );
			this.checkText();
			
			//图片
			var imgs = data.pic,
				html = [];
			if( typeof(imgs) === 'string' )
				imgs = [imgs];  //转换为数组
			
			var len = imgs.length;
			if( len>0 ){
				for(var i=0;i<len;i++){
					var li = '<li class="'+ (i >= 5 ? 'hidden' : '') +'" onmouseover="this.className=\'hover\'"  onmouseout="this.className=\'\'" >';
					li += '<a href="#"><img height="90" src="'+ imgs[i] +'">'+ ( i<3 ? '<span class="select"></span>' : '' ) +'</a>';
					li += '</li>';
					html.push( li );
				}
				this.jqPicArea.removeClass('hidden');
			}
			this.jqImgList.html(html.join(''));

			//分页数据
			var self = this,
				c = 5,  //每页条数
				ap = Math.ceil(len/c), //总页数
				cp = 0;  //当前页
			if( len > c ){
				$('#prev,#next').unbind(); //移除旧的事件
				this.ableBtn( $('#next') );
				$('#prev,#next').click(function(){
					if( $(this).hasClass(this.id + '-disable') )
						return false;

					if( this.id == 'prev' )
						cp = cp - 1 > 0 ? cp - 1 : 0;
					else
						cp = cp + 1 < ap ? cp + 1 : ap - 1;
					
					var start = cp * c, end = (cp+1) * c - 1;
					if( end > len-1 )
						end = len-1;
					
					self.jqImgList.find('li').each(function(i,item){
						if(  start <= i && i <= end )
							item.className = '';
						else item.className = 'hidden';
					});
					
					if( cp == 0 || cp == ap-1 )
						self.disableBtn( $(this) );
					self.ableBtn( this.id == 'prev' ? $('#next') : $('#prev') );
					
					return false;
				})
			}else
				self.disableBtn( $('#next') );
			return this;
		},
		disableBtn : function ( jqbtn ){
			var text = jqbtn.text(),
				prefix = text == '上一页' ? 'prev' : 'next';
			jqbtn.addClass( prefix+'-disable' )
			   .html(text);
		},
		ableBtn : function ( jqbtn ){
			var text = jqbtn.text(),
				clsPrefix = text == '上一页' ? 'prev' : 'next';
			jqbtn.removeClass( clsPrefix+'-disable' )
			   .html('<a href="#">'+text+'</a>');
		},
		
		/* 接口方法 pickUpDataFromPage  从页面抓取数据 */
		pickUpDataFromPage : function( trdType, relData ){
			return X.mod.trdShare.pick_upContentAndPicFromPage( X.getCfg('page'), trdType, relData );
		},
		
		/* 接口方法 getPostParam 获取待发送数据 */
		getPostParam : function(){
			// 参数说明
			// pic：图片地址  
			// title：人人网标题
			// url：人人网链接地址
			// trd_id：第三方id 1.新浪 2.腾讯 3.人人 逗号分隔
			// text：微博内容
			// comment_type：是否需评论回推(默认2)是否需评论回推 1.需要 2.不需要
			// id：需要评论回推时的本站id
			var p = {
				trd_id : this.trd_id,    
				text: this.jqInputor.val(),
				pic: ''
			}
			if( this.trd_id == 3 ){
				p.url = location.href;
				p.title = '自游网';
			}
			return p;
		},
		
		/* 接口方法 post 发布 */
		post : function(){
			var self = this,
				left = this.checkText();
				
			if( !left ){
				this.jqInputor.focus();
				return false;
			}
			if( self.lockPost )
				return false;
			self.lockPost = true;
			
			var urls = [];
			this.jqImgList.find('li>a').each(function(i,item){
				if( $(item).find('span.select')[0] ){
					urls.push( $(item).find('img')[0].src );
				}
			})

			var p = self.getPostParam();
			if( urls.length < 2 ){
				if( urls[0] ) 
					p.pic = urls[0];
				send(p);
			}
			else{
				//多张先拼图, 得到后端拼成的图的url
				Req.jsApiCall('shareApi','createImage',{urls: urls.join(',')},function(r1){
					if(r1.isOk()){
						var d = r1.getData();
						if(d.url) p.pic = d.url;
						send(p);
					}
					else MB.confirm('提示',r1.getMsg()+'. 是否取消图片,继续分享?',function(id){ 
						id=='ok' && send(p); 
					});
				},'POST',{asyn: false})   //取消异步
			}
			
			function send( param ){
				Req.jsApiCall('shareApi','share', param,function(r2){
					if(r2.isOk()){
						self.close();
						MB.success('提示','分享成功');
					}
				},'post',{asyn: false});
				self.lockPost = false; 
			}
		}
	},cfg || {}));
	
	X.reg('shareBox',sharebox,true);
	
	return sharebox;
});

//第三方帐号列表，用于勾选分享的场境使用
X.reg('ThirtyAccountCheckList', Util.create(Base, {
    autoRender : true,
    
    onViewReady : function() {
        //调用 api ,查询已绑定的帐户
        Req.bindLst(getUid(), Util.bind(this.onReqLoaded, this));
    },
    
    //API返回后的结果处理
    onReqLoaded : function(r) {
        var html = '';
        if (r.isOk()) {
            var data = r.getData(),
                thirtys = {
                    sina : {name : '新浪微博'},
                    qq : {name : '腾讯微博'},
                    renren : {name : '人人网'}
                };

            var thirty, htmls = [], id, xwbId = this.cacheId;
            for (var sv in data) {
                thirty = thirtys[sv];
                if (thirty) {
                    id = sv + '_check_' + xwbId;
                    htmls.push('<label for="'+id+'" class="checkbox"><input id="'+id+'" type="checkbox" value="'+sv+'" checked="checked" />'+thirty.name+'</label>');
                }
            }
            
            if (htmls.length) {
                html = '分享：' + htmls.join('');
            }
        }
        
        this.jq().html(html);
    }
}));

X.reg('RtePhotoInsertPanel', Util.create(ui.Dialog, {
    dlgContentHtml : 'insetImg',
    title:'插入图片',
    appendTo: 'body',
    closeable:true,
    
    //mod.GroupPost 实例
    xRte : null, 
    
    cs : 'win-insert-img win-insert-img-s1 win-fixed',
    defBtn : 'ok',
    buttons : [                                        
            {title: getText('确&nbsp;定'),     id :'ok', cs:'btn-s1'},
            {title: getText('取&nbsp;消'),     id :'cancel',cs:'btn-s1 btn-s1-gray'}
    ],
    afterShow : function(b){
        this.get3rdAlbum();
    },
    bindList : {},  //已知的绑定列表
    get3rdAlbum : function(){ 
        var self = this;
        Req.getAlbumsService( function(r){
            if( r.isOk() ){
                var data = r.getData().enabled;
                for(var s in data){
                    if( self.bindList[s] ) //已经绑定过
                        return ;
                    self.bindList[s] = true;
                    var info = data[s].info;
                    
                    $('<a href="#" content-id="'+ s +'" type="'+s+'" uid="'+ data[s].data.id +'"><span>'+info.tips+'</span></a>').appendTo( self.jq("#tab") );
                    $( T.parse('picBox', {'boxId': s}) ).insertAfter(self.jq('#tab'));
                }
            }
        });
    },
    onViewReady:function(){
        
        var self = this, xRte = this.xRte , editer = xRte.editor;
        self.jq().addClass('win-insert-fla');
        self.jq('#xwb_dlg_btns').css('float','right').cssDisplay(0);
        
        self.jq('#tab').delegate('a', 'click', function(){
            var $this = $(this), 
                contentId = $this.attr('content-id');
            if( self.jq('#tab>a.cur').attr('content-id') == contentId ){
                return ;
            }
            var Movie = self.thisMovie('Xwb_MultiUpload');
            if( Movie.flashCallback && Movie.flashCallback('state') ){
                MsgBox.confirm('提示','正在上传图片，确定要切换吗？',function(rid){
                    if(rid=="ok"){
                        Movie.flashCallback('pause');
                        self.clearFlashData(); 
                        $this.click();
                    }
                    this.close();
                });
                return ;
            }
            
            self.jq('#tab>a').removeClass('cur');
            $this.addClass('cur');
            
            self.jq('.box').addClass('hidden');
            
            self.jq( '#'+ contentId ).removeClass('hidden');
            self.jq('#Btn_wbPicBox').cssDisplay(0);
            
            if( contentId === 'flashBox' ){   //flash上传
                self.jq().addClass('win-insert-fla');
                self.jq('#xwb_dlg_btns').cssDisplay(0);
            }
            else if( contentId === 'networkBox' ){   //网络url上传
                self.jq().removeClass('win-insert-fla win-insert-img-s1');
                self.jq('#xwb_dlg_btns').cssDisplay(1);
            }
            else {    //第三方相册上传
                self.jq().removeClass('win-insert-fla');
                self.jq().addClass('win-insert-img-s1');
                self.jq('#xwb_dlg_btns').cssDisplay(0);
                
                self.jq('#Btn_wbPicBox').cssDisplay(1);
                
                var $box = self.jq('#'+$this.attr('content-id'));
                if( $box.data('hasQuery') )   //已查询过
                    return;
                
                var type = $this.attr('type'), uid = Xwb.cfg.uid;
                Req.getAlbums(  type, uid, function( r ){
                    if( r.isOk() ){
                        var data = r.getData();
                        if( data.length <= 0 ){
                            $box.find('div.hd').html('相册列表为空');
                            return ;
                        }
                        $box.data('hasQuery', true);
                        var html = ['<select><option value="0">请选择相册</option>'];
                        for(var i=0; i<data.length; i++)
                            html.push('<option value="'+data[i].album_id+'">'+data[i].caption+'</option>');
                        html.push('</select>');
                        var $se = $( html.join('') );
                        
                        $box.find('div.hd').html( html.join('') );
                        
                        $box.find('select').change( function(){
                            var v = this.value;
                            if( v == 0 ) return ;
                            self.jq('#'+$this.attr('type')+' ul').html(T.parse('Loading'));
                            Req.getPhotosList( type, v, function(r){
                                if(r.isOk()){
                                    var html="",data = r.getData();
                                    if(data.length > 0){
                                        $(data).each(function(){
                                            this.original_pic = this.original_pic.replace(/:/ig,'\\:')
                                            html+= T.parse('albumItem',this);
                                        });
                                    } else {
                                        html = "该相册没有图片";
                                    }
                                    self.jq('#'+$this.attr('type')+' ul').html( html );
                                } else {
                                    MsgBox.alert('提示',r.getMsg());
                                }
                            });
                        });
                    }
                });
            }
        });
        
        X.use('action').reg('sp',function(e){   //从第三方插入图片, 在编辑器里显示中图, 发表时显示大图
            if(editer.enableDesign){
                e.lock(1);
                var img = new Image();
                var imgSrc = e.src.getAttribute('originalPic').replace('\\','');
                img.src = imgSrc;
                function netImgOnload() {
                    e.lock(0);
                    if( img.width <50 || img.height<50 ){
                        MsgBox.alert('提示','抱歉，该张图片太小了。\r\n图片不能小于50*50像素。');
                        return ;
                    }
                    if( img.width <= 300 || img.height <=300 )
                        xRte.insertNetImg( imgSrc );
                    else {
                        var size = Util.uniformScaleZoom(img.width, img.height, 300, 300, 1);
                        xRte.insertNetImg( imgSrc, size.width, size.height );
                    }
                }
                if(img.complete) 
                    netImgOnload.call(img);
                else 
                    img.onload = netImgOnload;;
            } else {
                MsgBox.alert('提示','请切换到富文本编辑模式再尝试插入图片！');
            }
        });
		
		var upUrl =  escape('http://'+location.host+Req.jsAPI('youjiApi','uploadPhoto'));   
		var plet = X.use('pipeMgr').getByType('group.topic_edit_editor');  //让后台可配置该上传接口
		if( plet.ui && plet.ui.cfgData &&  plet.ui.cfgData.upload_url )
			upUrl =  escape(plet.ui.cfgData.upload_url);

			
        var flash = X.ui.getFlash({
            src: X.request.basePath + 'flash/multiUpload.swf?v=' + X.getCfg('subver'),
            width: 614,
            height: 400,
            id:'Xwb_MultiUpload',
            name:'Xwb_MultiUpload',
            quality: 'high',
            w3c : 1,
            allowFullscreen: 'true',
            flashvars: 'jsFunc=flashCallback&_PHPSESSID='+$('#_PHPSESSID').val()+'&upload_url='+ upUrl +'&max_size=' + (10*1024*1024),
            AllowScriptAccess:"sameDomain",
            wmode: 'opaque'
        });

        win.flashCallback = function(type,data){
             if(__debug) console.log('type:'+type,'-----------data:'+data);
            switch(type){
                case 'ablum_id' :
                    return '12345';
                case 'allsuccessurl' :
                    self.successCallback(data);
                    break;
                case 'successurl' :
                    self.onSuccess(data); 
                    break;
                case 'close' :
                    self.close();
                    break;
            }
        }
        this.jq('#flashBox').html( flash );
        
        this.jq('#additem').click(function(){
            var captionDom = self.jq('.item:last').find('#caption');
            if(self.jq('.item').length < 5 && self.chkurl(captionDom.val())){
                var clone = self.jq('.item:eq(0)').clone();
                $(this).before(clone);
                clone.find('#caption').val('').focus();
            } else {
                captionDom.focus();
            }
            return false;
        });
        
        this.jq('#Btn_wbPicBox_close').click(function(){
            self.close();
        });
    },
    
    succCount: 0,
    uploadedImgData: [],
    
    allErrCount: 0,
    errorData: {},  // { ecode:{ count:1,err:err  }} 
    collectionErr: function( ec ){
        if( ec ){
            this.allErrCount++;
            if( this.errorData[ec] )
                this.errorData[ec].count++;
            else 
                this.errorData[r.getCode()] = {count: 1, err:r.getError()};
        }
    },
    clearFlashData: function(){
        this.succCount = 0;
        this.uploadedImgData = [];
        
        this.allErrCount = 0;
        this.errorData = {};
    },
    
    successCallback : function(data){
        var self = this, xRte = this.xRte;
        var    btns =  [{title:'继续上传照片',id:'cancel', cs: 'btn-s1'},{title:'插到帖子',id:'ok', cs: 'btn-s1'}];
        if(self.succCount === 0)
            btns = [{title:'重新上传照片',id:'cancel', cs: 'btn-s1'},{title:'完成',id:'ok', cs: 'btn-s1'}];

        var htmlTips = [];
        if( self.succCount>0 || ( self.succCount == 0 && self.allErrCount == 0 ) )
            htmlTips.push('成功上传'+self.succCount+'张照片。');
        
        if( self.allErrCount>0 ){
            //for(var ec in self.errorData){
                htmlTips.push( self.allErrCount+'张照片上传失败，请重新上传。');
            //}
        }
        
        X.use('Dlg',{
            appendTo: document.body,
            title:'提示',
            dlgContentHtml : 'MsgDlgContent',
            defBtn:'ok',
            mask : true,
            hasErr: self.allErrCount,
            imgData: self.uploadedImgData,
            buttons: btns,
            onbuttonclick:function(id){
                xRte.batchInsertImg( this.imgData ); //批量插入
                if(id == 'ok'){
                    this.close();
                    self.close();
                }
            },
            onViewReady:function(){
                this.jq('#xwb_msgdlg_ct').html(  htmlTips.join('<br/>') );
                if( !this.hasErr )
                    this.jq('#xwb_msgdlg_icon')[0].className = 'icon-success';
            }
        }).display(1);
        this.clearFlashData();   //清空该次上传图片返回的所有 成功/错误信息 的数据
    },
    onSuccess : function(json){
        var r = new Req.DefaultResponseDefinition( $.parseJSON(json) );
        //判断数据是否正确
        if( r.isOk() ){   
            var flashRst = r.raw.rst[0]; // 这里flashRst的数据也可能会出错
            if( flashRst && !flashRst.err ){
                this.succCount++;
                this.uploadedImgData.push(r); //插入图片改为全部上传后
            }
            else    
                this.collectionErr( r.getCode() );
        }
        else     
            this.collectionErr( r.getCode() );
    },
    display : function(b){
        var j = this.jq();

        if(b === undefined)
            return j.css('visibility') != 'hidden';
        b = !b;
        if(this.hidden !== b){
            if(!b) {
                this.hidden = b;
                j.css('visibility', '');
                this.beforeShow() !==false;
                this.afterShow();
            }else {
                if(this.beforeHide() !== false){
                    this.hidden = b;
                    j.css('visibility', 'hidden');
                    this.afterHide && this.afterHide();
                }
            }
        }
        return this;
    },
    close : function(){
        var self = this;
        var Movie = this.thisMovie('Xwb_MultiUpload');
        try {
            if( Movie.flashCallback && Movie.flashCallback('state')){
                MsgBox.confirm('提示','正在上传图片，确定要关闭吗？',function(rid){
                    if(rid=="ok"){
                        Movie.flashCallback('pause');
                        self.clearFlashData(); 
                        X.ui.Base.prototype.close.call(self);
                    }
                });
            } else {
                X.ui.Base.prototype.close.call(self);
            }
        } catch(e){
            X.ui.Base.prototype.close.call(self);
        }
    },
    thisMovie : function(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return win[movieName];
         } else {
             return document[movieName];
         }
    },
    uploadImgCount : 0,
    uploadlock : false,
    uploadImgCallBack : function(r){
        this.uploadImgCount--;
        if(r.isOk()){
            this.xRte.insertImg(r);
        } else {
            MsgBox.alert('提示',r.getMsg());
        }
        this.chkUpLoad();
    },
    chkUpLoad:function(){
        if(this.uploadImgCount==0 && !this.uploadlock){
            this.jq('#xweibo_loading').remove();
            this.close();
        }
    },
    onbuttonclick :function(id){
        var self = this;
        //网络图片上传
        if(id == "ok"){
            //self.uploadImgCount = 0;
            var itemList = this.jq('.item');
            //self.uploadlock = true;
            //self.jq('#networkBox').append(Tpl.parse('Loading'));
            for(var i=0,len = itemList.length;i<len;i++){
                var url = itemList.eq(i).find('#caption').val();
                if(self.chkurl(url))
                      self.xRte.insertNetImg(url);
                itemList.eq(i).find('#caption').val('');  //清空
                if( i != itemList.length-1 )
                    itemList.eq(i).remove(); //移除
            }
        }
    },
    chkurl:function(url){
        var reg = /^(http[s]?):\/\/[^\/\.]+?.+\w$/i;
        return reg.test(url);
    }
}));

X.mod.baiduMap = X.reg('BaiduMap', Util.create(Base, {
		map : NULL,
		mapNode : 'gmap',
		zoom : 5,
		//center : ["116.39825820922851", "39.904600759441024"],
		center : ['108.943176','34.292396'],
		footsInit : NULL,
		_markerInfoWin : NULL,
		_infoContents : NULL,
		canClick : true,
		canDrag : true,
		minZoom : 3,
		canZoom : true,
		canClickMark : false,
		
		hasNav : true,	
		viewCtl : true,
		maxZoom : 19,
		unToCenter : false,
		init : function(cfg){
			//初始化本实例的足迹
			this.foots = {};
			this.markers = {};
			this._infoContents = {};
			base.init.call(this, cfg);
		},
		
		innerViewReady : function(){
			var bm = new BMap.Map(this.mapNode,{minZoom:this.minZoom,maxZoom:this.maxZoom});			
			bm.centerAndZoom(this.createPoint(this.center[0], this.center[1]), this.zoom);
			
			bm.enableScrollWheelZoom();	
			
			this.map = bm;
			
			this.hasNav && ( bm.addControl(new BMap.NavigationControl({type:(this.navType?BMAP_NAVIGATION_CONTROL_SMALL:BMAP_NAVIGATION_CONTROL_LARGE)})) ); 
			!this.canDrag && (bm.disableDragging());			
			
			var self = this;			
			
			this.initFoots(this.foots);
			if (this.viewCtl){
				var floatSelect = this.jq('#floatSelect');
				floatSelect.cssDisplay(this.noAbroad);
				
				floatSelect.find('select').change(function(){
                    self.chgViewCtl(Number(this.value));
                });
				
				
				floatSelect.find('.home-abroad a').click(function(e){
					e.preventDefault();					
					var $area = $(this), v = $area.attr('rel');
					floatSelect.find('.curr').removeClass('curr');
					$area.addClass('curr');
					self.onMarkerClose.call(self);
					if(v == 1){
						self.setZoom.call(self, self.zoom);
						self.setCenter.call(self,self.center[0], self.center[1]);						
					}else{
						self.setCenter.call(self, '0' , '0');
						self.setZoom.call(self, 3);
					}					
				});
			}
		},
		
		createPoint : function(lat, lng){
			if(!lat || !lng) return new BMap.Point(this.center[0], this.center[1]);
			return new BMap.Point(lat, lng);
		},
		
		setZoom : function(zoom){
			this.map.setZoom(zoom);			
		},
		
		setCenter : function(lat, lng){
			this.map.panTo(this.createPoint(lat, lng));
		},
		
		changeFootState : function(spots_id, toState){
			var foots = this.foots, markers = this.markers;
			
			if (foots[spots_id])
				foots[spots_id].state = toState;
			
			if (markers[spots_id]) {
				markers[spots_id].setIcon(this.getFootImage(toState));
			}
		},
		
		//足迹初始化
		initFoots : function(foots, updateCount){
			updateCount = updateCount === undefined ? true: updateCount;
			
			if (foots){
				this.addFoots(foots);

				//updateCount && this.updateFootCounter();
			}
		},
		
		//批量添加足迹
		addFoots : function(foots){
			var map = this.map, self = this;
			for(var i in foots){
				if(typeof foots[i].state == 'object'){
					this.addFoot(map, foots[i].state, foots[i]);
				}else{
					//var d = {state:1, name:'asdasdf', lat: this.center[0], lng:this.center[1]};
					this.addFoot(map, Number(foots[i].state || 2), foots[i]);
				}
			}
		},
		
		//在地图上添加足迹
		/**
		* @param map {object} GOOGLE MAPS OBJECT
		* @param type {int} 1: 想去 2：去过的
		* @param spots {Object} 足迹的经纬度坐标等
		* @param cfg {function} 回调
		*/
		markerOpen : false, //已点击marker，不再运行点击地图方法
		addFoot : function(map, type, data, cfg){	
			var spots = data.spots || data;
 			var point = this.createPoint( spots.lng, spots.lat);
			var marker = new BMap.Marker(point, {
				icon : this.getFootImage(type)
			});  // 创建标注
			map.addOverlay(marker);              // 将标注添加到地图中
			cfg && cfg(marker);
			marker.setTitle(spots.name); 
			var self = this;
			if(this.canClickMark)
				marker.addEventListener("click", function(){ 
					self.markerOpen = true;
					self.onMarkerClick.call(self,marker, this)
				});  			
			spots.state = type;
			marker.sdt = spots;
			var spots_id = spots.id;
			data.spots && (spots.fid = data.id);
            this.foots[spots_id] = spots;
            this.markers[spots_id] = marker;
			return marker;
			
		},
		
		//footimages
		_footImages : {},
		
		//获取地图图标，如想去的、去过的，以及阴影
		getMapIcon : function(type){	
			if(typeof type != 'object'){
				var iconUrl = '';
				switch (Number(type)) {
					case 1:
						iconUrl = '/img/map_want.png';		
					break;
					
					case 2:
						iconUrl = '/img/map_been.png';			
					break;
					
					case 'shadow':
						return new google.maps.MarkerImage(
							'/img/shadow.png',
							new google.maps.Size(59, 32),
							new google.maps.Point(0, 0),
							new google.maps.Point(16, 32)
						);
					break;		
				}
				
				return new BMap.Icon(iconUrl,new BMap.Size(21, 66)
						,{ offset: new BMap.Size(0, 0),
						   imageOffset: new BMap.Size(0, 0)
				  });
				

			}else{
				return new BMap.Icon(type.img || '/img/shadow.png', new BMap.Size(22, 33), {
					offset: new BMap.Size(0, 0),                  // 指定定位位置				
					imageOffset: new BMap.Size(0,- type.points) //显示局部图片
			   });
			   
			}			
		},

		getFootImage : function(type){
			if(typeof type == 'string'){
				if (!this._footImages[type]) {
					var img = this.getMapIcon(type);//new google.maps.MarkerImage('/img/' + this.getMapIcon(type));
					this._footImages[type] = img;
				}
			}else{
					var img = this.getMapIcon(type);//new google.maps.MarkerImage('/img/' + this.getMapIcon(type));
					return img;
			}
			return this._footImages[type];
		},
		
		removeFoot : function(spots_id) {
			if (this.foots[spots_id]){
				delete this.foots[spots_id];
			}
			if (this.markers[spots_id]) {
				this.markers[spots_id].remove();
				delete this.markers[spots_id];
			}
		},
		
		//移除所有点
		removeAll : function() {
			for (var spot_id in this.foots) {
				this.removeFoot(spot_id);
			}
			this.foots = {};
			this.markers = {};
		},
		
		chgViewCtl : function(val){
			var markers = this.markers , tmpDat;			
			this.closeMarkerInfo();
			
			var bounds, visible, position = [], mapBounds = this.map.getBounds(), outBound = false;
			for (var i in markers) {
 				tmpDat = markers[i].sdt;
				if(val == 3 || tmpDat.state == val){
					markers[i].show();
					position.push(markers[i].getPosition());					
				}else{
					markers[i].hide();
				}				
			}
			if(position.length){
				var v = this.map.getViewport(position);
				this.setCenter(v.lat,v.lng);
			}
			
			this.view_mode = val;
		},
		
		closeMarkerInfo : function(){
			this.onMarkerClose && this.onMarkerClose();
			this._markerInfoWin && this._markerInfoWin.close();			
		},
		
		//修改足迹内容
		/**
		* @param foots {Array} GOOGLE MAPS OBJECT
		*/
		setFoot : function(foots){
			var tFoots = this.foots;
			for(var i = 0, j = foots.length; i<j; i++){
				var f = foots[i];
				tFoots[f.id] && $.extend(tFoots[f.id], f);
			}
		},
		
		//小标签提示
		showTips : function(msg){
			var tip = this._tip;
			if (!tip) {
				tip = X.use('base',{
					view : 'MapTip',
					appendTo : $('#'+this.mapNode),
					
					setContent : function(html){
						this.getView();
						this.jq('#tipC').html(html);
					},
					
					show : function(msg){
						if (msg) this.setContent(msg);
						
						this.display(1);
						
						var $jq = this.jq(), self = this;
						
						$jq.stop(TRUE)
						.css('opacity', 1)
						.show()
	/*                     .fadeOut(2500, function(){
							self.display(0);
						}); */
						setTimeout(function(){
							$jq.animate( {'opacity': 0}, 1500, function(){self.display(0)})
						},1000);
					}
				});
				
				this._tip = tip;
			}
			
			//<p>成功添加<span>广东</span><span>深圳</span>为你去过</p>
			tip.show(msg);
		},
		
		onMarkerClick : function(marker, _t){
			if (this.clickEnabled === false) return;
			if(X.cfg.mymap)
				this.showMarkerInfo(marker, _t);
			else{
				this.showMarkerInfo(marker);				
			}
			
		},
		
		showMarkerInfo : function(marker, param){
			var info = this.getMarkerInfo();
			var spots = marker.sdt,
				contentNode = info.getContent(),
				newContentNode = this.getMarkerInfoContent(spots, param);
				
			if (contentNode !== newContentNode){
				info.setContent(newContentNode);
			}
			info.disableAutoPan();
			marker.openInfoWindow(info);  
			//X.use('action', {target:info.getContent(),actions:X._cls.action.actions})
			
			$(info.getContent()).unbind('click').click(Util.bind(this.clickWin, this));
			this.setCenter(spots.lng, spots.lat);

		},
		
		_circle : null,
		onMarkerClose : function(){
			//先检查圈是否存在，存在即关闭
			//再关闭窗口
			if(this._markerInfoWin && this._markerInfoWin.isOpen()){
				this.markerOpen = false;
				this._markerInfoWin.close();
			}
			if(this._circle && this._circle.isVisible()){
				this._circle.hide();
			}
		},
		
		getMarkerInfo : function(size){
			size = size || {x:-0,y:-25}
			if (!this._markerInfoWin) {
				//google 地图包
				var opts = {
					offset : new BMap.Size(size.x, size.y)
				}
				var infoWin =  new BMap.InfoWindow('2', opts);
				
				infoWin.addEventListener('clickclose', Util.getBind(this, 'onMarkerClose'));
				
				this.map.addEventListener('zoomstart', Util.getBind(this, 'onMarkerClose'));
				
				this._markerInfoWin = infoWin;
			}
			return this._markerInfoWin;
		},
		
		
		getMarkerInfoContent : function(spots, param){
			return '';
		},
		
		//检查某个景点的状态设置，想去、去过？
		checkPlaceState : function(spots_id){
			var foots = this.foots;

			return foots[spots_id] && foots[spots_id].state || 0;
		},
		
		//更新页面上的想去、去过的统计数字
		updateFootCounter : function() {
			var foots = this.foots;
			if (foots){
				var nums = {1: 0, 2: 0}, foot = {};
				
				for (var i in foots) {
					foot = foots[i];
					
					if (foot.id) {
						nums[foot.state]++;
					}
				}
				
				X.fire('footmark.updateCounter', nums);
			}
		},
		
/* 		//点击地图
		clickMap : function(p){
			if(!this.markerOpen){
				var cir = new BMap.Circle(this.createPoint(p.point.lng, p.point.lat),100000);
				this.map.addOverlay(cir);
			}
		}, */

		staticimage : function(){
			//http://api.map.baidu.com/staticimage?center=116.403874,39.914889&width=400&height=300&zoom=11&markers=116.288891,40.004261|116.487812,40.017524|116.525756,39.967111|116.536105,39.872374|116.442968,39.797022|116.270494,39.851993|116.275093,39.935251|116.383177,39.923743&markerStyles=l,A|m,B|l,C|l,D|m,E|,|l,G|m,H
			var fts = this.foots, markers = [];
			for(var ft in fts){
				markers.push(fts[ft].lng+','+fts[ft].lat);
			}
			return markers.join('|');			
		}
}));

X.mod.extBaiduMap = X.reg('ExtBaiduMap', Util.create(X.mod.baiduMap, {
	//XHR查询对象
	xhr : null,
	
	//当前页码
	page : 1,
	
	//每页数据量
	limit : 10,
	
	//点击地图事件
	clickEnabled : TRUE,
	
	actionMgr : true,
	
	updateOnIdle: true,
	
	focusCS : 'search-box-s2-focus',
	
	rightLists : true, //右边列表
	
	canClick : true,
	
	addMarkAnimation : function(marker, num, fn){
		var self = this;
		if(num>0)
			setTimeout(function(){
				if(num%2 == 0){
					marker.hide();
				}else{
					marker.show();
				}
				num = num -1;
				self.addMarkAnimation(marker, num, fn);
			},100)
		else
			fn & fn();
	},

	onactiontrig : function(e) {
		switch (e.get('e')) {
		case 'sd' : //分享到微博冒泡
			e.stopPropagation(false);
		break;					
		case 'prev':
			this.prevPage();
		break;

		case 'next':
			this.nextPage();
		break;
		
		case 'addspot':
			var val = e.get('nst'), id = e.get('id'), self = this,
				goText = val == 1 ? '想去的地方': '去过的地方'
				,operText = '添加';
				spots = this.foots[id];
				var msg = '成功'+operText+'<span>' + spots.name + '</span>为你' + goText;
			if(val == 1){//去过								
					Req.addWantTo(id, function(r){
						if(r.isOk()){
							self.showTips(msg);
						}
					})
			}else{
					Req.addJourney('','','','','',id, 0,'', 0, function(r){
						if(r.isOk()){
							self.showTips(msg);										
						}
					})
			}
			self._markerInfoWin.close();
			e.preventDefault(false);
			
		break;
		
		case 'setspot':
			if(e.src.tagName.toUpperCase() == 'TD') return;
			
			this.clickAddSpots = true;
			
			var                 
				//当前的状态
				st = e.get('st'),
				
				spots_id = e.get('id'),
				
				//new State
				val = e.get('nst'),
				
				saveState = 0,
				
				spots,							
				
				param = {},
				
				textDesc,

				val_set = val;
				//新增加
				if (st == 0){
					spots = {
						lat : e.get('lat'),
						lng : e.get('lng'),
						name : e.get('name'),
						id : spots_id,
						state : val
					};																
				}
				
				var self = this;
				var msg, operText, goText;
				
				
				function addWantTo(newFoot){
					Req.addWantTo(spots_id, function(r){
						if(r.isOk()){
							complete(r);
						}
					})
				}
				
				function journeyAdd(newFoot){
					Req.addJourney('','','','','',spots_id, 0,'', 0, function(r){
						if(r.isOk()){
							complete(r);
						}
					})
				}
				
				function complete(er){
					if (val_set !=0 && saveState < 3){
						goText = val == 1 ? '想去的地方': '去过的地方';
						operText = saveState == 1 ? '添加': '修改';
						msg = '成功'+operText+'<span>' + spots.name + '</span>为你' + goText;
						if(st != 0) self.setFoot([{id:spots_id, fid : er.getData()}]);
						if(st == 0){
							spots.fid = er.getData();
						}											
						if(saveState == 1){
							var footMark = self.addFoot(self.map, val, spots, function(m){
								var num = val == 2 ? 8 : 12;
								self.addMarkAnimation(m, num, function(){
									if(val == 2){											
										if(er.getData().data.pop)self.onMarkerClick.call(self, footMark, 'call');
									}
								});
							});

						}									
					}
					self.updateFootCounter();				
					e.save('st', val_set, 'st');
					if(val_set == 0) msg = '成功删除<span>' + spots.name + '</span>';
					if(spots.name)
						self.showTips(msg);									
					if (saveState === 3) {
						$(e.src).removeAttr('checked');
					}
				}
				
				function delFoot(){
					val_set = 0;
					spots = self.foots[spots_id];
					self.removeFoot(spots_id);
					saveState = 3;
					complete('');
				}
				if(st == 0 ){
					if(val == 1){//想去
						param = {sid:spots_id};
						addWantTo();
					}else if(val == 2){//去过
						param = {sid:spots_id, type:0};
						journeyAdd();
					}
					saveState = 1;								
				}else{//先删除
					spots = this.foots[spots_id];							
					if(st == 1){//想去
						Req.delWantTo(spots_id, function(r){
							if(r.isOk()){
								if(st != val){
									saveState = 2;
									journeyAdd();
									self.changeFootState(spots_id, val);
								}else{
									delFoot();
									saveState = 3;
								}												
							}
						});
					}else{//去过 
						//Req.journeyDel('', spots_id, function(r){
						//	if(r.isOk()){
								if(st != val){
									saveState = 2;
									addWantTo();
									self.changeFootState(spots_id, val);
								}else{
									MB.confirm('提示','确定从足迹中删除此景点？',function(id){
										if(id=='ok'){
											Req.journeyDel('', spots_id, function(r){
												if(r.isOk()){
													saveState = 3;
													delFoot();
												}});
										}
									})
								}
						//	}
						//});
					}
				}
				e.preventDefault(false);
				this.closeMarkerInfo();
		break;
		
		//批量设置
		case 'setbspot':
			var $form = $(e.src).closest('FORM');
			var data = [],
				rows = $form.serializeArray(),
				spots,
				$rowEl
				foots = this.foots
				delayData = [];
			for (var i = 0, l = rows.length, name, row, value; i < l; i++) {
				row = rows[i];
				spots_id = row.name.split('_')[1];
				value = row.value;
				if(foots[spots_id] && foots[spots_id].fid)
					data.push(spots_id + ':' + value +':'+foots[spots_id].fid);
				else
					data.push(spots_id + ':' + value);
				
				$rowEl = $('#near_row_' + spots_id);
				
				if ($rowEl.length) {
					var kv = Util.parseKnV($rowEl.attr('rel'));
					if (kv){
						spots = {
							lat : kv.lat,
							lng : kv.lng,
							name : kv.name,
							id : spots_id,
							state : value
						};
						delayData.push({v: value, spots:spots});
						//this.addFoot(this.map, value, spots, { animation: google.maps.Animation.DROP });
					}
				}
			}
			
			
			//this.updateFootCounter();
			var len = data.length;
			if (len) {
				var self = this;
					Req.batchSetFm({p:data.join(',')}, function(ret){
						if (ret.isOk()) {
							self.setFoot(ret.getData());
							self.showTips('设置成功！');
							self.updateFootCounter();
							var red =  ret.getData();
							for(var i=0;i<len;i++){
								delayData[i].spots.fid = red[i].fid;
								self.addFoot(self.map, delayData[i].v, delayData[i].spots, function(m){
											self.addMarkAnimation(m, 12, function(){});
									});
							}
						}else{
							MB.alert('',ret.getMsg());
						}
					})
			}
			
			this.closeMarkerInfo();
			
			break;
			
			case 'aj':
				var n = e.get('n'), id = e.get('id');
				var c = X.use('JourneyInfo', {
					appendTo : 'body',
					hasArea : {name:n, id:id},
					closeable : true,
					mask : true,
					_title : '添加我的旅途',
					area : n,
					destroyOnClose:true,
					cs : 'win-fixed win-journey-map win-journey-add',
					showTips : function(msg, obj){
						obj = obj ? obj : this.jq('#tips');
						obj.text(msg).cssDisplay(1);		
					},
					afterSelect : function(data){
						self.afterSelect.call(self, data);					
					},
					contentHtml : 'JourneyInfo',
					save : function(e){
						e.preventDefault();
						var data = this.getInfo(), self = this;
						if(data !== false){//保存旅程
							Req.addJourney(data.time[0], data.time[1], data.story,'','',id,1,n, 1, function(r){									
								if(r.isOk()){
									self.close();
									MB.tipOk('添加成功');
								}else{
									self.showTips.call(self, r.getMsg());
								}
							});
						}
					}
				})
				c.display(1);
				
				this._markerInfoWin.close();
				
			break;
			
			case 'cancel' : 
				this._markerInfoWin.close();
			break;
			
			case 'cl':
				var spots_id = e.get('id'), self = this;
				var val = $(e.src).closest('.win-journey-check').find('input:checked').val();
				if(val == 2){
					MB.confirm('提示','你确认要删除该足迹同时也删除该足迹的旅程？',function(id){
						if(id=='ok'){
							self.removeFoot(spots_id);
							self.updateFootCounter();
							Req.journeyDel('', spots_id, function(r){
								if(r.isOk()){
									self.showTips('清除成功。');
								}});
						}
					})
				}else{
					this.removeFoot(spots_id);
				　　this.updateFootCounter();
					Req.delMark({sid :spots_id}, function(ret){
						if (ret.isOk()) {
							self.showTips('清除成功。');
						}
					})
				}
			break;
			}
	},
	
	clickWin : function(e){
		e.preventDefault(false);
		var obj = $(e.target), p = obj.closest('div.BMap_bubble_content')[0], rels = X.ax.ActionMgr.wrapRel(e.target, p);
		if(e.target.tagName.toUpperCase() == 'INPUT' && obj.attr('type') == 'radio'){
			var ch = obj.attr('checked');
			setTimeout(function(){
				obj.attr('checked',true)
			},10)
		}
		if(!rels) return;
		rels.evt = e;
		rels.src = e.target;
		
		this.onactiontrig(rels);
	},
	
	                
	reqComplete : function(ret) {
		if (ret.isOk()) {
			var data = ret.getData();
			this.showResult(data);
			this._lastData = data;
		}
		this.xhr = null;
	},
	
	showResult : function(data){
		if (data === undefined) {
			data = this._lastData;
		}
		
		if (!data) return;
		var spots = data.spots;
		 var 
			htmls = [],
			self = this,
			state = 0,
			inputHtml,
			kvStr,
			checkStr = ' checked="true"',
			inputName = '',
			rid;
				
		$.each(spots, function(i, r){
			rid = r.id;
			state = self.checkPlaceState(rid);
			inputName = 'result_' + rid;
			inputHtml = '<td><input  type="radio" rel="e:setspot,nst:2" value=1 name="'+inputName+'"'+(state == 2 ? checkStr:'')+'/></td><td><input  type="radio" rel="e:setspot,nst:1" value=2 name="'+inputName+'"'+(state == 1 ? checkStr:'')+'/></td>';
			kvStr = Util.encodeKnV({
				id: r.id,
				lat: r.lat,
				lng : r.lng,
				st : state,
				name : r.name
			});
			
			htmls.push('<tr' + (i%2 ? '': ' class="odd"') + ' rel="'+kvStr+'"><td>'+r.name+'</td>'+inputHtml+'</tr>');
		});

		this.jq('#result').html(htmls.join(''));

		var $page = this.jq('#page');
		if (spots.length == this.limit || this.page > 1) {
			spots.length == this.limit? $page.find('#nextPage').replaceWith('<span class="next" id="nextPage"><a rel="e:next" href="#">下一页</a></span>')
			: $page.find('#nextPage').replaceWith('<span class="next next-disable" id="nextPage">下一页</span>');
			
			this.page > 1? $page.find('#prevPage').replaceWith('<span class="prev" id="prevPage"><a rel="e:prev" href="#">上一页</a></span>') 
			: $page.find('#prevPage').replaceWith('<span class="prev prev-disable" id="prevPage">上一页</span>');
			$page.cssDisplay(1);
		} else {
			$page.cssDisplay(0);
		}
	},
	
	nextPage : function(){
		this.updatePlace(this.page + 1);
	},
	
	prevPage : function() {
		this.page > 1 && this.updatePlace(this.page - 1);
	},
	
	updatePlace : function(page){
		if (!this.updateOnIdle) return;
		
		var map = this.map,
			bounds = map.getBounds();
			
			this.page = page = page || 1;
		
		if (bounds){
			this.xhr && this.xhr.abort();
			this.xhr = null;
			var sw = bounds.getNorthEast(),
				ne = bounds.getSouthWest();
			this.xhr = Req.getSpotsByDM(sw.lat+','+sw.lng, ne.lat+','+ne.lng, this.limit, 1, page, Util.getBind(this, 'reqComplete'));
		}
	},
	
	clickAddSpots : false, //直接点击右边列表
	                
	onViewReady : function(cfg) {
		var map = this.map;
		if(this.canClick){
			var refreshResult = (function(inst){
				return function(d){
					if (!inst.updateOnIdle) return;
					inst.showResult();
				}
			})(this);
			
			//X.on('footmarkApi.setFm', refreshResult);
			X.on('batchSetFm.batchSetFm', refreshResult);
		}
		
		this.jq('#foot_search').cssDisplay(1);
		
		if(this.rightLists){ //是否绑定右边列表
			var self = this,
			
				updatePlace = function(){ self.updatePlace();},//Util.getBind(this, 'updatePlace'),
				
				updateTimer = null,
				
				delayUpdate = function(){ 
 					if(self.clickAddSpots){
						self.clickAddSpots = false;
						return;
					} 
					updateTimer && win.clearTimeout(updateTimer);
					updateTimer = setTimeout(updatePlace, 500);
				};
			
			this.map.addEventListener('moveend', delayUpdate);
		
			var footmap = this;
			function initSearch(){
				var search = X.use('search', {
					inputor : $('#foot_search_input'),
					focusCS : footmap.focusCS,
					defaultText : '去过或想去哪里？',
					view : footmap.jq('#foot_search')[0],
					catchClick: true,
					onEnter : function(e, row){
						var rid = row.id, zoom = self.map.getZoom();
						if (!footmap.checkPlaceState(rid)){
							Req.setFm({sid:rid, state:2}, function(e){
								if (e.isOk()) {
									footmap.setFoot([{id:rid,fid:e.getData()}]);
									
									//var isMove = footmap.pointIsContains(row.lat,row.lng);
									function _addFoot(){
										footmap.showTips('成功添加<span>' + row.name + '</span>为你去过的');
										//描点到地图上
										footmap.addFoot(self.map, 2, {
											name : row.name,
											id : rid,
											lat : row.lat,
											thumbnail_data: row.thumbnail_data,
											lng : row.lng
										}, function(m){
											self.addMarkAnimation(m, 12, function(){});
										});										
									}
									self.map.setViewport([self.createPoint(row.lng,row.lat)]);
									self.map.setZoom(zoom);
									_addFoot();									
								}else{
									MB.alert('',e.getMsg());
								}
							});
						}else{
							self.map.setViewport([self.createPoint(row.lng,row.lat)]);
							self.map.setZoom(zoom);
							footmap.showTips('你已添加过<span>' + row.name + '</span>');			
						}
						this.search.reset();
						this.search.display(0);
						
						$(this.inputor).focus();
					}
				});
				$('#foot_search a').click(function(e){
					e.preventDefault();
					search.search.onEnter({type:'keydown'});
					return false;
				});
			}
			setTimeout(function(){
				initSearch();
			}, 1000);
			//触发查询
		}
		if(this.rightLists) delayUpdate();
		if(this.canClick)
			map.addEventListener('click', Util.getBind(this, 'onMapClick'));
	},
	
	onMapClick : function(e) {		
		if (!this.clickEnabled ||this.markerOpen) return;
		
		this.onMarkerClose();
		
		var latLng = e.point, zoom = this.map.getZoom(), radius;

		//清除未完成的xhr查询
		this._nearXhr && this._nearXhr.abort();
		//计算半径
		switch (zoom) {
		case 3:
		case 4:
			radius = 100;
		break;
		
		case 5:
		case 6:
			radius = 50;
		break;
		
		case 7:
			radius = 30;
		break;
		
		case 8:
			radius = 15;
		break;
		
		case 9:
		case 10:
		case 11:
			 radius = 5;
		break;
		
		case 12:
		case 13:
			radius = 2;
		break;
		case 14:
		case 15:
		case 16:
		case 17:
		case 18:
		case 19:
			radius = 1;
		break;
		
		default:
			radius = 50;
		}
		//if(__debug)console.log('radius:'+radius)
		var self = this;
		this._nearXhr = Req.getSpotsNearPoint(latLng.lat+','+latLng.lng, radius, 3, function(r){
			if (r.isOk()) {
				var data = r.getData();
				self.showSpotsNear(latLng, data, r.getRequestCfg());
			}			
			self._nearXhr = null;
		});

	},
	
	showSpotsNear : function(latLng, data, cfg){
		var spots = data.spots, len = spots.length, spots_num = 0;	
		if(len == 0) return;
		var info = this.getMarkerInfo({x:-5,y:5});
		var htmls = [
			'<form><div class="win-journey-place"><h4 class="title">添加我的足迹</h4><div class="add-fp"><table cellpadding="0" cellspacing="0" class="fp-operate">',
			'<colgroup><col /><col class="col-opera"><col class="col-opera"></colgroup>',
			'<thead><tr><th></th><th>去过</th><th>想去</th></tr></thead><tbody>'
		];

		function getRowData(row){
			var us = {};
			us.lat = row.lat;
			us.lng = row.lng;
			us.name = row.name						
			return Util.encodeKnV(us);
		}
		
		for (var i = 0, row, ip_name, row_id, enStr; i < len; i++) {
			row = spots[i];
			row_id = row.id;
			
			if (this.checkPlaceState(row_id)) continue;
			
			ip_name = 'near_' + row_id;
			
			enStr = getRowData(row);
			var odd = !(i%2)?'odd':'';
			
			htmls.push('<tr class="'+odd+'" rel="'+enStr+'" id="near_row_'+row_id+'"><td class="first">'+row.name+'</td><td><input type="radio" name="'+ip_name+'" value=2></td><td><input type="radio" name="'+ip_name+'" value=1></td></tr>');
			spots_num++;
		}
		
		if (!spots_num) return;
		
		var circle = this.getCircle(latLng);

		htmls.push('</tbody></table></div><div class="btn-area"><a href="#" class="btn-s4" rel="e:setbspot"><span>确定</span></a></div></div></form>');		
		
		circle.show();
		
		circle.setCenter(this.createPoint(latLng.lng, latLng.lat));
		
		circle.setRadius(this.getRadius());
		
		var html = $(htmls.join(''));	
		info.content = html[0];		
		info.disableAutoPan();		
		
		this.map.openInfoWindow(info, latLng);      // 打开信息窗口
		$(info.getContent()).unbind('click').click(Util.bind(this.clickWin, this));
		
		this.setCenter(latLng.lng, latLng.lat);

	},

	getCircle : function(p, createIfNull) {
		createIfNull = createIfNull === undefined || createIfNull;
		if (!this._circle && createIfNull){
			var cir = new BMap.Circle(this.createPoint(p.lng, p.lat),this.getRadius());
			this.map.addOverlay(cir);
			this._circle = cir;
		}
		
		return this._circle;
	},
	
	getRadius : function(){
		var zoom = this.map.getZoom(),radius = {3:10000, 4:10000, 5:10500, 6:10500, 7:10500, 8:500, 9:3000, 10:2000, 11:1000, 12:900, 13:850, 14:425, 15:300, 16:100, 17:50 , 18:50, 19:50};
		//if(__debug)console.log('zoom:'+zoom)
		return radius[zoom];
	},
	
	getMarkerInfoContent : function(spots, param){
		var key = spots.id;
		//if (!this._infoContents[key]) {
			var checkStr = ' checked="true"', 
				
				state = Number(spots.state),
				
				KnV = Util.encodeKnV({
					st : state,
					id : key
				}),
				
				radio_name = 'spotstate_' + key;
			var img = '';
			if (spots.thumbnail_data && spots.thumbnail_data.square_pic)
				img = '<img src="'+  spots.thumbnail_data.square_pic +'" class="show">';
			//var height = Util.byteLen(spots.name)>25 ? 120 : 120; 	

			if(X.cfg.mymap){ //我的旅途地图
				var del = '<a class="btn-s5" href="#" rel="e:cl"><span>删除</span></a>';
				if(param == 'call')  del = '<a class="btn-s5" href="#" rel="e:cancel"><span>取消</span></a>';
				this._infoContents[key] = $('<div class="win-journey-check"  rel="'+KnV+'">'+
					'<h4 class="place-name">'+spots.name+'</h4><div class="operate">'+
						'<p><label class="radio" for="been-to"><input rel="e:setspot,nst:2" value="2" type="radio" name="'+radio_name+'"'+(state == 2 ? checkStr:'')+'>我去过</label><label class="radio" for="want-go"><input value="1" rel="e:setspot,nst:1" type="radio" name="'+radio_name+'"'+(state == 1 ? checkStr:'')+'>我想去</label></p>'+
					'</div><div class="btn-area"><a class="btn-s4" href="#" rel="e:aj,n:'+spots.name+'"><span>添加至旅途首页</span></a>'+del+'</div>'
				+'</div>')[0];
			}else{
				this._infoContents[key] = $('<div class="win-journey-check" rel="'+KnV+'">'+
					'<h4 class="place-name">'+spots.name+'</h4><div class="operate">'+
					'<p class="desc">'+spots.have_been_user+'位用户去过这里，'+spots.want_to_user+'位用户想去这里</p>'+
					'<p><label class="radio" for="been-to"><input rel="e:addspot,nst:2" value="2" type="radio" name="'+radio_name+'">我去过</label><label class="radio" for="want-go"><input  rel="e:addspot,nst:1" value="1" type="radio" name="'+radio_name+'">我想去</label></p>'+
				+'</div>')[0];
				//this._infoContents[key] = $('<div class="fp-info-inner" style="height:'+height+'px;" rel="'+KnV+'"><h3>'+spots.name+'</h3>'+img+'<p><label><input rel="e:setspot,nst:1" type="radio" name="'+radio_name+'"'+(state == 1 ? checkStr:'')+'>想去</label></p><p><label><input  rel="e:setspot,nst:2" type="radio" name="'+radio_name+'"'+(state == 2 ? checkStr:'')+'>去过</label></p><p><a href="#" rel="e:cl">清除</a></p></div>')[0];
			}
	   // }	   
		return this._infoContents[key];
	}
}))


X.reg('ShowInfo', Util.create(Base,{
	view : '',
	itemTag : 'li',
	hideTag : '.hide-cont',
	eventType : 'mouseover',
	onViewReady : function() {
		var self = this;
		this.jq(this.itemTag).each(function(){
			var _t = $(this);
			if(self.effect) self.effect.call(_t);
			else
				if(self.eventType != 'click'){
					var ht = _t.find(self.hideTag);
					_t.mouseover(function(e){
						var hts = self.getShow.call(self);
						if(hts) hts.cssDisplay(0)
						ht.cssDisplay(1);
					}).mouseout(function(e){
						//ht.cssDisplay(0);
					});
				}else{
					_t.click(function(){
						var ht = _t.find(self.hideTag);
						var hts = self.getShow.call(self);
						ht.cssDisplay(1);
					})
				}
		})
	},
	
	getShow : function(){
		var hts = this.jq(this.hideTag);
		for(var i=0,len = hts.length;i<len;i++){
			if(!hts.eq(i).hasClass('hidden')){
				return hts.eq(i);
			}
		}
	}
	
}))

})(Xwb, jQuery);
